package com.mzj.saas.mservice.lockManager.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.tokenizer.Result;
import cn.hutool.extra.tokenizer.TokenizerEngine;
import cn.hutool.extra.tokenizer.TokenizerUtil;
import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.*;
import com.mzj.saas.commons.enums.BacklogItemTypeEnum;
import com.mzj.saas.commons.enums.HouseLockOperatorLogTypeEnum;
import com.mzj.saas.commons.enums.LockAuthTypeEnum;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.area.entity.Area;
import com.mzj.saas.mservice.area.repository.AreaRepository;
import com.mzj.saas.mservice.backlog.entity.BacklogItem;
import com.mzj.saas.mservice.backlog.entity.BacklogItemPerson;
import com.mzj.saas.mservice.backlog.repository.BacklogItemPersonRepository;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRepository;
import com.mzj.saas.mservice.community.entity.Community;
import com.mzj.saas.mservice.community.repository.CommunityRepository;
import com.mzj.saas.mservice.community.service.AppCommunityService;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.eligible.entity.DepartmentEnterpriseTagRef;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentEnterpriseTagRefRepository;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.house.entity.Cohabit;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.entity.HouseMatchUser;
import com.mzj.saas.mservice.house.repository.CohabitRepository;
import com.mzj.saas.mservice.house.repository.HouseMatchUserRepository;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.house.repository.LockFrozenRepository;
import com.mzj.saas.mservice.lock.Repository.*;
import com.mzj.saas.mservice.lock.entity.*;
import com.mzj.saas.mservice.lock.service.LockAppService;
import com.mzj.saas.mservice.lock.vo.LockStatusVo;
import com.mzj.saas.mservice.lockManager.entity.HouseLockOperatorLog;
import com.mzj.saas.mservice.lockManager.entity.LockHouseSetting;
import com.mzj.saas.mservice.lockManager.entity.SmartLockBrand;
import com.mzj.saas.mservice.lockManager.entity.SmartLockUser;
import com.mzj.saas.mservice.lockManager.repository.HouseLockOperatorLogRepository;
import com.mzj.saas.mservice.lockManager.repository.LockHouseSettingRepository;
import com.mzj.saas.mservice.lockManager.repository.SmartLockBrandRepository;
import com.mzj.saas.mservice.lockManager.repository.SmartLockUserRepository;
import com.mzj.saas.mservice.lockManager.vo.*;
import com.mzj.saas.mservice.property.entity.CommunityHouseUser;
import com.mzj.saas.mservice.property.entity.MatchUser;
import com.mzj.saas.mservice.property.entity.MatchUserHouse;
import com.mzj.saas.mservice.property.repository.CommunityHouseUserRepository;
import com.mzj.saas.mservice.property.repository.MatchUserHouseRepository;
import com.mzj.saas.mservice.property.repository.MatchUserRepository;
import com.mzj.saas.mservice.smartlock.service.SmartLockBrandService;
import com.mzj.saas.mservice.smartlock.service.haixiaoke.SmartLockHxkService;
import com.mzj.saas.mservice.smartlock.service.tianwanghulian.FourEventHandleService;
import com.mzj.saas.mservice.smartlock.service.tianwanghulian.SmartLockTWHlService;
import com.mzj.saas.mservice.smartlock.service.yaluete.SmartLockYltService;
import com.mzj.saas.mservice.smartlock.service.youdian.SmartLockYdService;
import com.mzj.saas.mservice.smartlock.vo.DevMacStateVO;
import com.mzj.saas.mservice.smartlock.vo.DynamicPasswordVO;
import com.mzj.saas.mservice.smartlock.vo.SmartLockVO;
import com.mzj.saas.mservice.smartlock.vo.yaluete.YltAuthorizationRecordVO;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.mservice.sys.service.UserService;
import com.mzj.saas.mservice.sys.utils.SqlUtils;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class LockManagerService {
    private static final Logger log = LoggerFactory.getLogger(LockManagerService.class);

    private static final String LOCK_ORDER = " ORDER BY l.operator_time DESC";
    private static final String ALARM_ORDER = " ORDER BY la.alarm_time DESC";
    private static final String SQL_PAGE = " LIMIT ? OFFSET ?";

    @Autowired
    private RedisService redisService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private SmartLockBrandService smartLockBrandService;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private BacklogItemPersonRepository backlogItemPersonRepository;
    @Autowired
    private LockHouseSettingRepository lockHouseSettingRepository;
    @Autowired
    private SmartLockBrandRepository smartLockBrandRepository;
    @Autowired
    private HouseLockOperatorLogRepository houseLockOperatorLogRepository;
    @Autowired
    private CommunityRepository communityRepository;
    @Autowired
    private SmartLockUserRepository smartLockUserRepository;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private HouseMatchUserRepository houseMatchUserRepository;
    @Autowired
    private CohabitRepository cohabitRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;
    @Autowired
    private LockAppService lockAppService;
    @Autowired
    private SmartLockPwdRepository smartLockPwdRepository;
    @Autowired
    private SmartLockCardRepository smartLockCardRepository;
    @Autowired
    private SmartLockFingerprintRepository smartLockFingerprintRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private SmartLockYltService smartLockYltService;
    @Autowired
    private AppCommunityService appCommunityService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private FourEventHandleService fourEventHandleService;
    @Autowired
    private MatchUserHouseRepository matchUserHouseRepository;
    @Autowired
    private MatchUserRepository matchUserRepository;
    @Autowired
    private SmartLockTWHlService smartLockTWHlService;
    @Autowired
    private SmartLockYdService smartLockYdService;
    @Autowired
    private SmartLockHxkService smartLockHxkService;
    @Autowired
    private SmartLockFaceRepository smartLockFaceRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HouseLockFrozenLogRepository houseLockFrozenLogRepository;
    @Autowired
    private LockFrozenRepository lockFrozenRepository;

    public ResultBean<List<LockBrandVO>> lockBrands(String accessToken) {
        try {
            List<LockBrandVO> lockBrands = jdbcTemplate.query("select b.id,b.name,b.logo_path as logoPath,b.qrcode_type as qrcodeType,\n" +
                            "b.qrcode_length as qrcodeLength from `saas_smart_lock_brand` b where b.status = 1 and b.del_status = 1",
                    new BeanPropertyRowMapper<>(LockBrandVO.class));

            return ResultBean.successfulResult(lockBrands);
        } catch (Exception e) {
            log.error("LockManagerService lockBrands Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> searchHouse(String accessToken, String search) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            // String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            if (enterpriseId == null) {
                return ResultBean.failedResultWithMsg("非企业用户");
            }

            DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
            if (hierarchy == null) {
                return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
            }
            Long areaTagId = hierarchy.getTagId();// 区域标签
            if (areaTagId == null) {
                return ResultBean.failedResultWithMsg("机构所对应区域标签为空");
            }
            String areaTag = "";
            if (areaTagId == 1) {
                areaTag = "province_id";
            } else if (areaTagId == 2) {
                areaTag = "city_id";
            } else if (areaTagId == 3) {
                areaTag = "district_id";
            } else if (areaTagId == 4) {
                areaTag = "street_id";
            } else if (areaTagId == 5) {
                areaTag = "community_id";
            }
            Long areaId = hierarchy.getAreaId();// 区域id

            if (StringUtils.isBlank(search)) {
                return ResultBean.failedResultOfParamWithMsg("搜索条件为空");
            }

            List<Object> args = new ArrayList<>();
            args.add("%" + search + "%");
            args.add("%" + search + "%");
            args.add(areaId);

            List<HouseVO> houseList = jdbcTemplate.query("SELECT h.`id` AS houseId,c.id as communityId,c.`name` AS communityName,b.id as buildId,b.`name` AS buildName,\n" +
                    "u.id as unitId,u.name AS unitName,h.`room_number` AS roomNumber,h.`address`,d.id as orgId,CASE h.house_nature WHEN 1 THEN d.name ELSE h.owner_name END AS orgName,\n" +
                    "a.name AS cityName,a2.name AS districtName \n" +
                    "FROM `saas_house` h LEFT JOIN `saas_community` c ON h.`residence_community_id` = c.`id`  \n" +
                    "LEFT JOIN `saas_community_build` b ON h.`building_num` = b.`id`\n" +
                    "LEFT JOIN `saas_community_build_unit` u ON h.`unit` = u.id\n" +
                    "LEFT JOIN `saas_department` d ON h.`org_id` = d.id\n" +
                    "LEFT JOIN `sys_area` a ON h.`city_id` = a.id\n" +
                    "LEFT JOIN `sys_area` a2 ON h.`district_id` = a2.id\n" +
                    "WHERE (h.audit_status = 1 OR h.house_nature != 1) AND (h.id like ? OR c.`name` LIKE ?) and h." + areaTag + " = ?", new BeanPropertyRowMapper<>(HouseVO.class), args.toArray());

            return ResultBean.successfulResult(houseList);
        } catch (Exception e) {
            log.error("LockManagerService searchHouse Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<ApiData<HouseVO>> searchHousebyCondition(String accessToken, String searchCondition, String houseContent, Long provinceId, Long cityId, Long districtIdyId, Long streetId, String residenceCommunityId, Long buildId, Long unitId, Integer roomNumber, Integer pageNumber, Integer pageSize) {
        try {
            log.info("searchHousebyCondition, searchCondition={}, houseContent={}, provinceId={}, cityId={}, districtIdyId={}, streetId={}, residenceCommunityId={}, "
                            + "buildId={}, unitId={}, roomNumber={}, pageNumber={}, pageSize={}", searchCondition, houseContent, provinceId, cityId, districtIdyId,
                    streetId, residenceCommunityId, buildId, unitId, roomNumber, pageNumber, pageSize);
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null)
                return ResultBean.failedResultOfToken();

            ApiData<HouseVO> apiData = new ApiData<>();
            Long enterpriseId = token.getEnterpriseId();
            DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
            if (hierarchy == null) {
                return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
            }
            Long id = hierarchy.getId();
            List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(id);
            List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签

            // 1、政府机构，根据区域标签所对应区域id查
            Long areaTagId = hierarchy.getTagId();// 区域标签
            Long areaId = null;
            if (enterpriseTagIds.contains(3L)) {
                areaId = hierarchy.getAreaId();// 区域id
            }
            String areaTag = "province_id";
            if (areaTagId == 1) {
                areaTag = "province_id";
            } else if (areaTagId == 2) {
                areaTag = "city_id";
            } else if (areaTagId == 3) {
                areaTag = "district_id";
            } else if (areaTagId == 4) {
                areaTag = "street_id";
            } else if (areaTagId == 5) {
                areaTag = "community_id";
            }

            Long hierarchyOrgId = null;
            if (enterpriseTagIds.contains(2L)) {
                hierarchyOrgId = hierarchy.getOrgId();
            }
            // 查询单位承租人机构下的房产信息
            Long unitLesseeId = null;
            if (enterpriseTagIds.contains(7L)) {
                unitLesseeId = hierarchy.getOrgId();
            }
            // 3、物业，查已绑定该物业的小区下的所有房产
            List<String> residenceCommunityIds = new ArrayList<>();
            if (enterpriseTagIds.contains(4L)) {
                List<Community> communities = communityRepository.findByOrgIdAndStatus(enterpriseId, 1);
                residenceCommunityIds = communities.stream().map(Community::getId).distinct().collect(Collectors.toList());// 小区id
            }
            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" and (sh." + areaTag + " = ? or sh.org_id = ? or sh.unit_lessee_id = ? or sh.residence_community_id in ");
            args.add(areaId);
            args.add(hierarchyOrgId);
            args.add(unitLesseeId);
            if (residenceCommunityIds != null && !residenceCommunityIds.isEmpty()) {
                where.append(SqlUtils.foreachIn(residenceCommunityIds.size()) + ")");
                args.addAll(residenceCommunityIds);
            } else {
                where.append("(null))");
            }

            // 省
            if (provinceId != null) {
                where.append(" and sh.province_id = ?");
                args.add(provinceId);
            }
            // 市
            if (cityId != null) {
                where.append(" and sh.city_id = ?");
                args.add(cityId);
            }
            // 区
            if (districtIdyId != null) {
                where.append(" and sh.district_id = ?");
                args.add(districtIdyId);
            }
            // 街道
            if (streetId != null) {
                where.append(" and sh.street_id = ?");
                args.add(streetId);
            }

            // 小区id
            if (StringUtils.isNotBlank(residenceCommunityId)) {
                where.append(" and sh.residence_community_id = ?");
                args.add(residenceCommunityId);
            }
            // 楼宇id
            if (buildId != null) {
                where.append(" and sh.building_num = ?");
                args.add(buildId);
            }
            // 单元id
            if (unitId != null) {
                where.append(" and sh.unit = ?");
                args.add(unitId);
            }
            // 房号
            if (roomNumber != null) {
                where.append(" and sh.room_number = ?");
                args.add(roomNumber);
            }

            if (StringUtils.isNotBlank(searchCondition)) {
                where.append(" and (sh.id like ? or sc.name like ? or b.name like ? or u.name like ? or sh.room_number like ? or sh.owner_name like ?)  ");  // 搜索关键字字段【小区、楼栋、单元、房号】省市区街道，房屋id
                args.add("%" + searchCondition + "%");
                args.add("%" + searchCondition + "%");
                args.add("%" + searchCondition + "%");
                args.add("%" + searchCondition + "%");
                args.add("%" + searchCondition + "%");
                args.add("%" + searchCondition + "%");
            }
            if (StrUtil.isNotBlank(houseContent)) {
                TokenizerEngine engine = TokenizerUtil.createEngine();
                Result result = engine.parse(houseContent);
                List<String> communityList = new ArrayList<>();
                while (result.hasNext()) {
                    communityList.add(result.next().getText());
                }

                where.append(" and ( ");
                for (String community : communityList) {
                    where.append(" sc.name like ? or ");
                    args.add("%" + community + "%");
                }
                // Pattern.compile接受一个标记参数flag，以调整匹配的行为，“\\d+”正则匹配数字
                // pattern.matcher查询字符串中的数字，matcher.find()，true匹配到数字，matcher.group()返回字符串中的全部数字,matcher.group()之后，matcher对象则已没有数字
                Pattern pattern = Pattern.compile("\\d+");
                Matcher matcher = pattern.matcher(houseContent);
                String matcherStr = null;
                if (matcher.find()) {
                    matcherStr = matcher.group();
                }
                if (StrUtil.isNotBlank(matcherStr)) {
                    where.append(" b.name = ? or ");
                    args.add(matcherStr);
                }
                if (StrUtil.isNotBlank(matcherStr)) {
                    where.append(" u.name = ? or ");
                    args.add(matcherStr);
                }
                if (StrUtil.isNotBlank(matcherStr)) {
                    where.append(" sh.room_number = ? or ");
                    args.add(matcherStr);
                }
                where.delete(where.length() - 3, where.length());
                where.append(") ");
            }
            // 不查询出合租房产下的子房产
            where.append(" and sh.housemate_id is null");
            String querySql = " SELECT sc.name AS communityName,b.name AS buildName,u.name AS unitName,a.NAME AS province,a2.NAME AS city, a3.NAME AS district, a4.NAME AS street, a5.NAME AS community,sh.id AS houseId,sh.building_num AS buildId,sh.unit AS unitId,sh.owner_user_id AS ownerUserId,sh.owner_name AS ownerName,sh.* FROM saas_house sh\n" +
                    " LEFT JOIN saas_community sc\n" +
                    " ON sc.id = sh.residence_community_id\n" +
                    " LEFT JOIN saas_community_build b \n" +
                    " ON sh.building_num = b.id\n" +
                    " LEFT JOIN saas_community_build_unit u\n" +
                    " ON sh.unit = u.id\n" +
                    " LEFT JOIN saas_department d \n" +
                    " ON sh.org_id = d.id\n" +
                    "  LEFT JOIN sys_area a\n" +
                    " ON sh.province_id = a.id\n" +
                    " LEFT JOIN sys_area a2\n" +
                    " ON sh.city_id = a2.id\n" +
                    " LEFT JOIN sys_area a3\n" +
                    " ON sh.district_id = a3.id\n" +
                    " LEFT JOIN sys_area a4\n" +
                    " ON sh.street_id = a4.id\n" +
                    " LEFT JOIN sys_area a5\n" +
                    " ON sh.community_id = a5.id\n" +
                    " WHERE (sh.audit_status = 1 OR sh.house_nature != 1) \n" +
                    " AND sh.id NOT IN \n" +
                    " ( SELECT h.id FROM saas_smart_lock l\n" +
                    " LEFT JOIN saas_house h\n" +
                    " ON h.id = l.house_id WHERE h.status = 1)\n";

            String countSql = " SELECT COUNT(1) FROM saas_house sh\n" +
                    " LEFT JOIN saas_community sc\n" +
                    " ON sc.id = sh.residence_community_id\n" +
                    " LEFT JOIN saas_community_build b \n" +
                    " ON sh.building_num = b.id\n" +
                    " LEFT JOIN saas_community_build_unit u\n" +
                    " ON sh.unit = u.id\n" +
                    " LEFT JOIN saas_department d \n" +
                    " ON sh.org_id = d.id\n" +
                    " LEFT JOIN sys_area a\n" +
                    " ON sh.province_id = a.id\n" +
                    " LEFT JOIN sys_area a2\n" +
                    " ON sh.city_id = a2.id\n" +
                    " LEFT JOIN sys_area a3\n" +
                    " ON sh.district_id = a3.id\n" +
                    " LEFT JOIN sys_area a4\n" +
                    " ON sh.street_id = a4.id\n" +
                    " LEFT JOIN sys_area a5\n" +
                    " ON sh.community_id = a5.id\n" +
                    " WHERE (sh.audit_status = 1 OR sh.house_nature != 1) \n" +
                    " AND sh.id NOT IN \n" +
                    " ( SELECT h.id FROM saas_smart_lock l\n" +
                    " LEFT JOIN saas_house h\n" +
                    " ON h.id = l.house_id WHERE h.status = 1)\n";

            Long count = jdbcTemplate.queryForObject(countSql + where, Long.class, args.toArray());

            // 查询分页数据
            String offsets = " limit ? offset ?";
            where.append(offsets);
            args.add(pageSize);
            args.add(pageNumber * pageSize);

            List<HouseVO> houseVOS = jdbcTemplate.query(querySql + where, new BeanPropertyRowMapper<>(HouseVO.class), args.toArray());
            // log.info(querySql + where + JSON.toJSONString(args));
            apiData.setTotal(count);
            apiData.setData(houseVOS);
            return ResultBean.successfulResult(apiData);
        } catch (Exception e) {
            log.error("LockManagerService searchHouse Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 安装智能锁
     *
     * @param accessToken
     * @param vo
     * @return 房屋安装智能锁 房内有成员自动将其记录为承租人 多个取第一个成员
     */
    public ResultBean<Object> lockSetup(String accessToken, LockSetupVO vo) {
        try {
            // 校验登录信息
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            // 企业id
            Long enterpriseId = tokenRedisVo.getEnterpriseId();

            if (vo == null) {
                return ResultBean.failedResultOfParamWithMsg("参数为空");
            }
            log.info("LockManagerService lockSetup params = {}", JSON.toJSONString(vo));

            Date date = new Date();
            // 锁类型：1房屋智能锁 2门禁智能锁
            Integer type = vo.getType();

            if (vo.getBrandId() == null) {
                return ResultBean.failedResultOfParamWithMsg("品牌为空");
            }

            SmartLock bySn = smartLockRepository.findBySn(vo.getMac());
            if (ObjectUtil.isNotNull(bySn)) {
                return ResultBean.failedResultWithMsg("此智能锁已经绑定房屋");
            }

            // 四代锁mac18位,如果不是18位不给添加
            if (vo.getBrandId() == 4) {
                if (vo.getMac().length() != 18) {
                    return ResultBean.failedResultOfParamWithMsg("请输入18位MAC地址");
                }
            }
            // 六代锁mac15位,如果不是15位不给添加
            if (vo.getBrandId() == 6) {
                if (vo.getMac().length() != 15) {
                    return ResultBean.failedResultOfParamWithMsg("请输入15位MAC地址");
                }
            }
            // 八代锁mac12位,如果不是12位不给添加
            if (vo.getBrandId() == 8) {
                if (vo.getMac().length() != 12) {
                    return ResultBean.failedResultOfParamWithMsg("请输入12位MAC地址");
                }
            }

            String sn = null;
            // 根据锁的mac获取sn
            ResultBean<String> resultBean = smartLockBrandService.getSnByMac(vo.getMac(), vo.getHouseId(), vo.getBrandId());
            if (resultBean != null && resultBean.getCode() != StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                log.info("lockSetup fail, resultBean={}", JSON.toJSONString(resultBean));
                // 设备注册和获取信息失败
                return ResultBean.failedResultOfParamWithMsg(resultBean.getMsg());
            }
            // 熙盟注册不返回设备id，通过事件返回
            if ((vo.getBrandId() == 1 || vo.getBrandId() == 3 || vo.getBrandId() == 4 || vo.getBrandId() == 5 || vo.getBrandId() == 6 || vo.getBrandId() == 7 || vo.getBrandId() == 8) && resultBean != null) {
                sn = resultBean.getResultData();
            }
            log.info("lockSetup sn = {}, brandId={}, resultBean={}", sn, vo.getBrandId(), JSON.toJSONString(resultBean));

            DevMacStateVO devMacStateVO = null;
            // 查询设备状态
            if (StringUtils.isNotEmpty(sn)) {
                // 调用锁的接口获取锁的状态
                ResultBean<DevMacStateVO> stateResult = smartLockBrandService.getState(sn, vo.getBrandId());
                if (stateResult != null && stateResult.getCode() == StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                    devMacStateVO = stateResult.getResultData();
                }
            }

            // mac获取安装记录
            SmartLock existLock = smartLockRepository.findByMac(vo.getMac());
            if (existLock != null) {
                return ResultBean.failedResultWithMsg("该智能锁已安装，不可重复安装");
            }

            SmartLock save = null;
            // 天网互联密码标识
            String identification = null;
            if (vo.getBrandId() == 4) {
                identification = "S" + System.currentTimeMillis() + RandomUtils.nextInt(1000, 10000);
            }
            if (type == 1) {// 房屋智能锁
                String houseId = vo.getHouseId();
                List<SmartLock> smartLocks = smartLockRepository.findByHouseId(houseId);
                if (!smartLocks.isEmpty()) {
                    return ResultBean.failedResultWithMsg("该房屋已安装智能锁");
                }

                Optional<House> houseOptional = houseRepository.findById(houseId);
                House house = houseOptional.get();

                SmartLock smartLock = new SmartLock();
                // smartLock.setName(vo.getName());
                smartLock.setIdentification(identification);
                smartLock.setMac(vo.getMac());
                smartLock.setSn(sn);
                smartLock.setBrandId(vo.getBrandId());
                smartLock.setBindType(1);// 单位
                smartLock.setBindStatus(1);// 单位绑定
                smartLock.setType(1);// 房屋智能锁
                smartLock.setHouseId(houseId);
                smartLock.setStatus(1);
                smartLock.setCommunityId(vo.getCommunityId());
                smartLock.setCommunityName(vo.getCommunityName());
                smartLock.setBuildId(vo.getBuildId());
                smartLock.setBuildName(vo.getBuildName());
                smartLock.setUnitId(vo.getUnitId());
                smartLock.setUnitName(vo.getUnitName());
                smartLock.setRoomNumber(vo.getRoomNumber());
                smartLock.setOrgId(house.getOrgId());
                if (devMacStateVO != null) {
                    smartLock.setElectricQuantity(devMacStateVO.getBattery());
                    smartLock.setOnlineStatus(devMacStateVO.getState());
                } else {
                    smartLock.setElectricQuantity(0);
                    smartLock.setOnlineStatus(0);
                }
                smartLock.setVolume(0);
                smartLock.setSignalLevel(1);
                smartLock.setOauthNumber(0);
                if (StringUtils.isBlank(sn)) {
                    smartLock.setMechineStatus(0);// 未激活
                } else {
                    smartLock.setMechineStatus(1);// 正常
                }
                smartLock.setOperatorId(userId);
                smartLock.setOperatorOrgId(enterpriseId);
                smartLock.setOperatorTime(date);
                smartLock.setTotalCloseDay(0);
                smartLock.setIsPersonPermission(1);

                if (house.getHouseNature() == 1) {// 公租房
                    smartLock.setHouseType(1);
                    // 已备案，同步用户数据
                    if (house.getRecordStatus() == 1) {
                        List<HouseMatchUser> houseMatchUser = houseMatchUserRepository.findHouseIdAndStatus(houseId, 1);
                        if (houseMatchUser.isEmpty()) {
                            log.warn("LockManagerService lockSetup, Leasing record does not exist, houseId={}", houseId);
                            return ResultBean.failedResultWithMsg("配租记录不存在");
                        }
                        // 多承租人取第一个承租人作为锁用户数据
                        HouseMatchUser oneMathUser = houseMatchUser.get(0);
                        AppUser user = appUserRepository.findByIdOrEnterpriseUserId(oneMathUser.getMatchUserId(), oneMathUser.getMatchUserId());
                        if (user == null) {
                            log.warn("LockManagerService lockSetup, Lessee does not exist, houseId={}", houseId);
                            return ResultBean.failedResultWithMsg("承租人不存在");
                        }
                        smartLock.setMatchUserId(oneMathUser.getMatchUserId());
                        smartLock.setMatchUserName(user.getName());
                        smartLock.setOrgId(house.getOrgId());
                        // 查询产权单位名称
                        if (house.getOrgId() != null) {
                            Optional<Department> dep = departmentRepository.findById(house.getOrgId());
                            if (dep.isPresent()) {
                                smartLock.setOrgName(dep.get().getName());
                            }
                        }
                        save = smartLockRepository.save(smartLock);

                        for (HouseMatchUser matchUser : houseMatchUser) {
                            // 生成承租人授权明细
                            SmartLockAuth matchAuth = new SmartLockAuth();
                            matchAuth.setLockId(save.getId());
                            matchAuth.setHouseId(houseId);
                            matchAuth.setBindType(0);// 单位
                            matchAuth.setMatchUserId(matchUser.getMatchUserId());
                            matchAuth.setAuthorUserId(matchUser.getMatchUserId());
                            AppUser user1 = appUserRepository.findByIdOrEnterpriseUserId(matchUser.getMatchUserId(), matchUser.getMatchUserId());
                            if (user1 == null) {
                                return ResultBean.failedResultWithMsg("承租人不存在");
                            }
                            matchAuth.setUserName(user1.getName());
                            matchAuth.setMobile(user1.getPhone());
                            matchAuth.setRelationTag(1);// 户主
                            matchAuth.setPwdStatus(0);
                            matchAuth.setFingerprintStatus(0);
                            matchAuth.setCardStatus(0);
                            matchAuth.setCpuStatus(0);
                            matchAuth.setBleStatus(0);
                            matchAuth.setCreateTime(date);
                            matchAuth.setUserType(1);
                            smartLockAuthRepository.save(matchAuth);

                            // 生成同住人授权明细
                            Long applyId = matchUser.getApplyId();
                            List<Cohabit> cohabits = cohabitRepository.findByApplyId(applyId);
                            for (Cohabit cohabit : cohabits) {
                                SmartLockAuth cohabitAuth = new SmartLockAuth();
                                cohabitAuth.setLockId(save.getId());
                                cohabitAuth.setHouseId(houseId);
                                cohabitAuth.setBindType(0);// 单位
                                cohabitAuth.setMatchUserId(matchUser.getMatchUserId());
                                cohabitAuth.setAuthorUserId(cohabit.getId());
                                cohabitAuth.setUserName(cohabit.getName());
                                cohabitAuth.setMobile(cohabit.getMobile());
                                cohabitAuth.setRelationTag(cohabit.getFamilyTiesType());
                                cohabitAuth.setPwdStatus(0);
                                cohabitAuth.setFingerprintStatus(0);
                                cohabitAuth.setCardStatus(0);
                                cohabitAuth.setCpuStatus(0);
                                cohabitAuth.setBleStatus(0);
                                cohabitAuth.setCreateTime(date);
                                cohabitAuth.setUserType(2);
                                smartLockAuthRepository.save(cohabitAuth);
                            }
                        }
                    } else {
                        smartLock.setOrgId(house.getOrgId());
                        save = smartLockRepository.save(smartLock);
                    }
                }

                if (house.getHouseNature() != 1) {// 房产
                    smartLock.setHouseType(2);
                    smartLock.setOrgName(house.getOwnerName());
                    List<CommunityHouseUser> tenantList = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);
                    String matchUserId = null;
                    String matchUserName = null;
                    // if (!tenantList.isEmpty()) {
                    //    CommunityHouseUser houseUser = tenantList.get(0);
                    //    matchUserId = houseUser.getUserId();
                    //    matchUserName = houseUser.getName();
                    //    smartLock.setMatchUserId(matchUserId);
                    //    smartLock.setMatchUserName(matchUserName);
                    //}
                    // 新增如果是单位承租人机构，存储单位承租人信息 xiaolong 20230315
                    List<MatchUserHouse> byHouseId2 = matchUserHouseRepository.findByHouseId(houseId);
                    if (!byHouseId2.isEmpty()) {
                        Long matchUserStockId = Long.valueOf(byHouseId2.get(0).getMatchUserStockId());
                        MatchUser byMatchUserIdAndDeleteStatus = matchUserRepository.findByIdAndDeleteStatus(matchUserStockId, false);
                        if (byMatchUserIdAndDeleteStatus != null) {
                            matchUserId = byMatchUserIdAndDeleteStatus.getMatchUserId();
                            matchUserName = byMatchUserIdAndDeleteStatus.getName();
                            smartLock.setMatchUserId(matchUserId);
                            smartLock.setMatchUserName(matchUserName);
                        }
                    }
                    if (!tenantList.isEmpty()) {
                        CommunityHouseUser houseUser = tenantList.get(0);
                        matchUserId = houseUser.getUserId();
                        matchUserName = houseUser.getName();
                        smartLock.setMatchUserId(matchUserId);
                        smartLock.setMatchUserName(matchUserName);
                    }


                    save = smartLockRepository.save(smartLock);

                    // 同步用户数据
                    List<CommunityHouseUser> houseUserList = communityHouseUserRepository.findByCommunityHouseIdAndStatus(houseId, 1);
                    if (!houseUserList.isEmpty()) {
                        for (CommunityHouseUser houseUser : houseUserList) {
                            SmartLockAuth auth = new SmartLockAuth();
                            auth.setLockId(save.getId());
                            auth.setHouseId(houseId);
                            auth.setBindType(0);// 单位
                            auth.setMatchUserId(matchUserId);
                            auth.setAuthorUserId(houseUser.getUserId());
                            if (houseUser.getType() == 1) {
                                auth.setUserType(1);
                            } else if (houseUser.getType() == 2) {
                                auth.setUserType(2);
                            } else if (houseUser.getType() == 3) {
                                auth.setUserType(3);
                            } else {
                                auth.setUserType(4);
                            }
                            auth.setUserName(houseUser.getName());
                            auth.setMobile(houseUser.getMobile());
                            auth.setPwdStatus(0);
                            auth.setFingerprintStatus(0);
                            auth.setCardStatus(0);
                            auth.setCpuStatus(0);
                            auth.setBleStatus(0);
                            auth.setFaceStatus(0);
                            auth.setCreateTime(date);
                            auth.setCommunityUserId(houseUser.getId());
                            smartLockAuthRepository.save(auth);
                        }
                    }
                    //    新增合租房产下房屋的成员信息，添加到智能锁授权表中，获取合租房产下的房屋
                    List<House> byHousemateIdAndStatus = houseRepository.findByHousemateIdAndStatus(houseId, 1);
                    for (House housemateIdAndStatus : byHousemateIdAndStatus) {
                        String id = housemateIdAndStatus.getId();
                        // 同步用户数据
                        List<CommunityHouseUser> houseUserList1 = communityHouseUserRepository.findByCommunityHouseIdAndStatus(id, 1);
                        if (!houseUserList1.isEmpty()) {
                            for (CommunityHouseUser houseUser : houseUserList1) {
                                // 新增智能锁授权指纹
                                String communityHouseId1 = houseUser.getCommunityHouseId();
                                List<SmartLock> byHouseId1 = smartLockRepository.findByHouseId(communityHouseId1);
                                if (byHouseId1.isEmpty()) {
                                    SmartLock smartLock1 = new SmartLock();
                                    List<SmartLock> byHouseId = smartLockRepository.findByHouseId(houseId);
                                    BeanUtils.copyProperties(byHouseId.get(0), smartLock1);
                                    smartLock1.setId(null);
                                    smartLock1.setHouseId(communityHouseId1);
                                    smartLock1.setStatus(2);
                                    smartLockRepository.save(smartLock1);
                                }
                                SmartLockAuth auth = new SmartLockAuth();
                                // 获取房屋id
                                String communityHouseId = houseUser.getCommunityHouseId();
                                List<House> byIdAndStatus = houseRepository.findByIdAndStatus(communityHouseId, 1);
                                if (byIdAndStatus.size() > 0) {
                                    // 设置合租房产下的房间号和子房屋id
                                    auth.setRoomNumber(byIdAndStatus.get(0).getRoomNumber());
                                    auth.setSubHouseId(communityHouseId);
                                }
                                auth.setLockId(save.getId());
                                auth.setHouseId(houseId);
                                auth.setBindType(0);// 单位
                                auth.setMatchUserId(matchUserId);
                                auth.setAuthorUserId(houseUser.getUserId());
                                if (houseUser.getType() == 1) {
                                    auth.setUserType(1);
                                } else if (houseUser.getType() == 2) {
                                    auth.setUserType(2);
                                } else if (houseUser.getType() == 3) {
                                    auth.setUserType(3);
                                } else {
                                    auth.setUserType(4);
                                }
                                auth.setUserName(houseUser.getName());
                                auth.setMobile(houseUser.getMobile());
                                auth.setPwdStatus(0);
                                auth.setFingerprintStatus(0);
                                auth.setCardStatus(0);
                                auth.setCpuStatus(0);
                                auth.setBleStatus(0);
                                auth.setFaceStatus(0);
                                auth.setCreateTime(date);
                                auth.setCommunityUserId(houseUser.getId());
                                smartLockAuthRepository.save(auth);
                            }
                        }
                    }
                }
            }

            if (type == 2) {// 门禁智能锁
                SmartLock smartLock = new SmartLock();
                // smartLock.setName(vo.getName());
                smartLock.setIdentification(identification);
                smartLock.setMac(vo.getMac());
                smartLock.setSn(sn);
                smartLock.setBrandId(vo.getBrandId());
                smartLock.setBindType(1);// 单位
                smartLock.setBindStatus(1);// 单位绑定
                smartLock.setType(2);// 门禁智能锁
                smartLock.setCommunityId(vo.getCommunityId());
                smartLock.setCommunityName(vo.getCommunityName());
                smartLock.setBuildId(vo.getBuildId());
                smartLock.setBuildName(vo.getBuildName());
                smartLock.setUnitId(vo.getUnitId());
                smartLock.setUnitName(vo.getUnitName());
                smartLock.setElectricQuantity(0);
                smartLock.setVolume(0);
                smartLock.setSignalLevel(1);
                smartLock.setOnlineStatus(0);
                smartLock.setOrgId(vo.getOrgId());
                smartLock.setOrgName(vo.getOrgName());
                if (devMacStateVO != null) {
                    smartLock.setElectricQuantity(devMacStateVO.getBattery());
                    smartLock.setOnlineStatus(devMacStateVO.getState());
                } else {
                    smartLock.setElectricQuantity(0);
                    smartLock.setOnlineStatus(0);
                }
                if (StringUtils.isBlank(sn)) {
                    smartLock.setMechineStatus(0);// 未激活
                } else {
                    smartLock.setMechineStatus(1);// 正常
                }
                smartLock.setOperatorId(userId);
                smartLock.setOperatorTime(date);
                smartLock.setTotalCloseDay(0);
                save = smartLockRepository.save(smartLock);
            }

            // 生成智能锁设置数据
            LockHouseSetting setting = new LockHouseSetting();
            setting.setLockId(save.getId());
            setting.setLowPowerValue(0);
            setting.setLowPowerStatus(0);
            setting.setVolumeValue(0);
            setting.setStrangerOpenStatus(0);
            setting.setPickProofStatus(0);
            setting.setDuressStatus(0);
            setting.setOperatorId(userId);
            setting.setLastUpdateTime(date);
            lockHouseSettingRepository.save(setting);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerService lockSetup Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<List<Map<String, Object>>> communityList(String accessToken, String cityName) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            Long enterpriseId = tokenRedisVo.getEnterpriseId();

            if (StringUtils.isBlank(cityName)) {
                return ResultBean.failedResultOfParamWithMsg("定位城市为空");
            }

            Area area = areaRepository.findByName(cityName);
            if (area == null) {
                return ResultBean.failedResultWithMsg("定位城市数据不存在");
            }
            Long cityId = area.getId();

            // 条件过滤：1定位城市，2已绑定用户机构
            List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT c.id AS communityId,c.`name` AS communityName FROM `saas_community` c WHERE c.`city_id` = ? AND c.`org_id` = ?", cityId, enterpriseId);

            return ResultBean.successfulResult(list);
        } catch (Exception e) {
            log.error("LockManagerService communityList Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> isLockSetup(String accessToken, String mac) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            if (StringUtils.isBlank(mac)) {
                return ResultBean.failedResultOfParamWithMsg("mac值为空");
            }

            SmartLock smartLock = smartLockRepository.findByMac(mac);
            Map<String, Object> map = new HashMap<>();
            if (smartLock != null) {
                map.put("flag", 0);// 已安装
                map.put("name", smartLock.getName());
            } else {
                map.put("flag", 1);// 未安装
            }

            return ResultBean.successfulResult(map);
        } catch (Exception e) {
            log.error("LockManagerService isLockSetup Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> verifyApply(String accessToken, String mac) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (StringUtils.isBlank(mac)) {
                return ResultBean.failedResultOfParamWithMsg("mac值为空");
            }

            AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
            if (appUser == null) {
                return ResultBean.failedResultWithMsg("用户不存在");
            }
            String phone = appUser.getPhone();

            SmartLock smartLock = smartLockRepository.findByMac(mac);
            if (smartLock == null) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }

            if (smartLock.getType() == 2) {
                return ResultBean.failedResultWithMsg("门禁锁不能进行此操作");
            }

            Optional<House> houseOptional = houseRepository.findById(smartLock.getHouseId());
            House house = houseOptional.get();
            Integer houseNature = house.getHouseNature();
            if (houseNature == 1) {
                return ResultBean.failedResultWithMsg("公租房锁不能进行此操作");
            }

            if (!phone.equals(house.getOwnerMobile())) {
                return ResultBean.failedResultWithMsg("非产权所有人，无操作权限");
            }

            if (smartLock.getBindType() == 2) {
                return ResultBean.failedResultWithMsg("智能锁已转个人，请解绑后再申请");
            }

            // 判断是否已有待办事项
            List<BacklogItem> items = backlogItemRepository.findByHouseIdAndTypeAndHandleStatus(house.getId(), BacklogItemTypeEnum.LOCK_BIND.getValue(), 0);
            if (!items.isEmpty()) {
                return ResultBean.failedResultWithMsg("智能锁转个人申请已存在");
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerService verifyApply Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    @Transactional
    public ResultBean<Object> toPersonLock(String accessToken, ConfirmVO vo) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();

            Date date = new Date();
            // 验证验证码
            String phone = redisService.getSmsCodeMobile(vo.getCode());
            if (!StringUtils.isBlank(phone)) {
                if (vo.getPhone().equals(phone)) {
                    AppUser user = appUserRepository.findByPhone(vo.getPhone());
                    if (user == null) {
                        return ResultBean.failedResultWithMsg("手机号码对应用户不存在");
                    }

                    SmartLock smartLock = smartLockRepository.findByMac(vo.getMac());
                    if (smartLock == null) {
                        return ResultBean.failedResultWithMsg("智能锁不存在");
                    }
                    String matchUserId = smartLock.getMatchUserId();
                    String houseId = smartLock.getHouseId();

                    // 生成待办事项
                    BacklogItem backlogItem = new BacklogItem();
                    backlogItem.setHouseId(houseId);
                    backlogItem.setOrgId(userService.findUserEnterpriseId(smartLock.getOperatorId()));
                    if (enterpriseId != null) {
                        backlogItem.setUserOrgId(enterpriseId);
                    }
                    backlogItem.setType(BacklogItemTypeEnum.LOCK_BIND.getValue());
                    backlogItem.setTitle("申请为个人智能锁");
                    backlogItem.setContent(smartLock.getCommunityName() + smartLock.getBuildName() + "栋" + smartLock.getUnitName() + "单元" + smartLock.getRoomNumber() + "号");
                    backlogItem.setBusinessStatus("待审批");
                    backlogItem.setHandleStatus(0);// 0未读/未处理
                    backlogItem.setOperatorId(userId);
                    backlogItem.setMatchUserId(matchUserId);
                    backlogItem.setPhone(user.getPhone());
                    backlogItem.setCreateTime(date);
                    BacklogItem save = backlogItemRepository.save(backlogItem);

                    BacklogItemPerson backlogItemPerson = new BacklogItemPerson();
                    backlogItemPerson.setBacklogItemId(save.getId());
                    backlogItemPerson.setLockId(smartLock.getId());
                    backlogItemPerson.setUserId(user.getId());// 个人用户id
                    backlogItemPerson.setAuditStatus(0);
                    backlogItemPersonRepository.save(backlogItemPerson);
                } else {
                    return ResultBean.failedResultWithMsg("验证码不正确");
                }
            } else {
                return ResultBean.failedResultWithMsg("验证码未找到或已过期");
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerService toPersonLock Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 智能锁列表
     *
     * @param accessToken
     * @param search
     * @param bindType      绑定类型:1单位 2个人
     * @param name
     * @param mac           智能锁mac
     * @param type          锁类型 1、房屋智能锁 2、门禁智能锁
     * @param houseId       房屋id
     * @param communityId   小区
     * @param buildId       楼宇
     * @param unitId        单元
     * @param roomNumber    房号
     * @param signalLevel   信号状态
     * @param onlineStatus  在线状态 1、在线 2、离线
     * @param orgName       产权所有人
     * @param matchUserName 承租人
     * @param oauthNumber   授权人数
     * @param oauthStatus   授权状态:0未授权，1已授权
     * @param mechineStatus 设备状态
     * @param pageNumber
     * @param pageSize      单位锁查询权限范围内的智能锁列表
     */
    public ResultBean<ApiData<LockManagerListVO>> lockList(String accessToken, String search, Integer bindType, String name, String mac, Integer type,
                                                           String houseId, String communityId, Long buildId, Long unitId, String roomNumber,
                                                           Integer signalLevel, Integer onlineStatus, String orgName, String matchUserName, Integer oauthNumber, Integer oauthStatus, Integer mechineStatus, Integer leaseStatus,
                                                           Integer pageNumber, Integer pageSize) {
        ResultBean<ApiData<LockManagerListVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<LockManagerListVO> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            // 绑定类型状态
            if (bindType == null) {
                return ResultBean.failedResultOfParamWithMsg("绑定类型为空");
            }

            // 校验登录信息
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            // 企业id
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            // 登录类型 1、企业 2、普通
            Integer loginType = tokenRedisVo.getLoginType();
            // 登录场景  1.PC端登录 2.APP登录
            Integer flag = tokenRedisVo.getFlag();

            String phone = null;
            if (flag == 1) {
                User user = userRepository.findById(userId);
                phone = user.getMobile();
            } else {
                AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
                phone = appUser.getPhone();
            }

            StringBuilder wheres = new StringBuilder();

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1 AND l.status != 2");
            // wheres.append(" where 1 = 1");

            if (bindType == 1) {// 单位锁
                // 智能锁授权表
                List<SmartLockAuth> authList = smartLockAuthRepository.findOrgLockAuth(userId, phone);
                // 智能锁绑定id
                List<Long> lockIds = authList.stream().map(SmartLockAuth::getLockId).distinct().collect(Collectors.toList());

                if (loginType == 1) { // 企业登录
                    DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
                    if (hierarchy == null) {
                        return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
                    }
                    // 拼接条件
                    List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(hierarchy.getId());
                    List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签

                    // 1、政府机构，根据区域标签所对应区域id查
                    Long areaId = null;
                    String areaTag = "province_id";
                    if (enterpriseTagIds.contains(3L)) {
                        Long areaTagId = hierarchy.getTagId();// 区域标签
                        if (areaTagId == null) {
                            return ResultBean.failedResultWithMsg("机构所对应区域标签为空");
                        }

                        if (areaTagId == 1) {
                            areaTag = "province_id";
                        } else if (areaTagId == 2) {
                            areaTag = "city_id";
                        } else if (areaTagId == 3) {
                            areaTag = "district_id";
                        } else if (areaTagId == 4) {
                            areaTag = "street_id";
                        } else if (areaTagId == 5) {
                            areaTag = "community_id";
                        }
                        areaId = hierarchy.getAreaId();// 区域id
                    }

                    // 2、产权单位，根据orgId
                    Long hierarchyOrgId = null;
                    if (enterpriseTagIds.contains(2L)) {
                        hierarchyOrgId = hierarchy.getOrgId();
                    }
                    // 查询单位承租人机构房产信息
                    Long unitLesseeId = null;
                    if (enterpriseTagIds.contains(7L)) {
                        unitLesseeId = hierarchy.getOrgId();
                    }
                    // 3、物业，查已绑定该物业的小区
                    List<String> residenceCommunityIds = new ArrayList<>();
                    if (enterpriseTagIds.contains(4L)) {
                        List<Community> communities = communityRepository.findByOrgIdAndStatus(enterpriseId, 1);
                        residenceCommunityIds = communities.stream().map(Community::getId).distinct().collect(Collectors.toList());// 小区id
                    }
                    // 新增查询房东机构房产信息 20230414 xiaolong
                    List<String> houseIds = new ArrayList<>();
                    if (enterpriseTagIds.contains(8L)) {
                        List<House> houses = houseRepository.findByOrgIdAndStatus(enterpriseId, 1);
                        houseIds = houses.stream().map(House::getId).distinct().collect(Collectors.toList());// 小区id
                        where.append(" and (h." + areaTag + " = ? or l.org_id = ?  or h.unit_lessee_id = ? or l.house_id in ");
                        args.add(areaId);
                        args.add(hierarchyOrgId);
                        args.add(unitLesseeId);
                        if (!houseIds.isEmpty()) {
                            where.append(SqlUtils.foreachIn(houseIds.size()) + ")");
                            args.addAll(houseIds);
                        } else {
                            where.append("(null))");
                        }
                    } else {
                        where.append(" and (h." + areaTag + " = ? or l.org_id = ? or h.unit_lessee_id = ? or l.community_id in ");
                        args.add(areaId);
                        args.add(hierarchyOrgId);
                        args.add(unitLesseeId);
                        if (!residenceCommunityIds.isEmpty()) {
                            where.append(SqlUtils.foreachIn(residenceCommunityIds.size()) + ")");
                            args.addAll(residenceCommunityIds);
                        } else {
                            where.append("(null))");
                        }
                    }
                } else {
                    where.append(" and (h.owner_mobile = ? or l.id in ");
                    args.add(phone);
                    if (!lockIds.isEmpty()) {
                        where.append(SqlUtils.foreachIn(lockIds.size()) + ")");
                        args.addAll(lockIds);
                    } else {
                        where.append("(null))");
                    }
                }
            }

            if (bindType == 2) {// 个人锁
                List<SmartLockUser> lockUserList = smartLockUserRepository.findPersonLockUser(userId, phone);
                List<Long> lockIds = lockUserList.stream().map(SmartLockUser::getLockId).distinct().collect(Collectors.toList());

                if (loginType == 1) {// 拼接企业id
                    where.append(" and l.operator_org_id = ?");
                    args.add(enterpriseId);
                } else {
                    where.append(" and (h.owner_mobile = ? or l.id in ");
                    args.add(phone);
                    if (!lockIds.isEmpty()) {
                        where.append(SqlUtils.foreachIn(lockIds.size()) + ")");
                        args.addAll(lockIds);
                    } else {
                        where.append("(null))");
                    }
                }
            }

            // 单位、个人
            where.append(" and l.bind_type = ? and l.bind_status = ?");
            args.add(bindType);
            args.add(bindType);

           /* if (leaseStatus != null && leaseStatus == 1){//出租状态

                if (bindType == 1) {//单位锁
                    List<SmartLockAuth> authList = smartLockAuthRepository.findOrgLockAuth(userId, phone);
                    List<Long> lockIds = authList.stream().map(SmartLockAuth::getLockId).distinct().collect(Collectors.toList());

                    if (loginType == 1) {
                        DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
                        if (hierarchy == null) {
                            return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
                        }
                        List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(hierarchy.getId());
                        List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());//用户企业标签

                        //1、政府机构，根据区域标签所对应区域id查
                        Long areaId = null;
                        String areaTag = "province_id";
                        if (enterpriseTagIds.contains(3L)) {
                            Long areaTagId = hierarchy.getTagId();//区域标签
                            if (areaTagId == null) {
                                return ResultBean.failedResultWithMsg("机构所对应区域标签为空");
                            }

                            if (areaTagId == 1) {
                                areaTag = "province_id";
                            } else if (areaTagId == 2) {
                                areaTag = "city_id";
                            } else if (areaTagId == 3) {
                                areaTag = "district_id";
                            } else if (areaTagId == 4) {
                                areaTag = "street_id";
                            } else if (areaTagId == 5) {
                                areaTag = "community_id";
                            }
                            areaId = hierarchy.getAreaId();//区域id
                        }

                        //2、产权单位，根据orgId
                        Long hierarchyOrgId = null;
                        if (enterpriseTagIds.contains(2L)) {
                            hierarchyOrgId = hierarchy.getOrgId();
                        }

                        //3、物业，查已绑定该物业的小区
                        List<String> residenceCommunityIds = new ArrayList<>();
                        if (enterpriseTagIds.contains(4L)) {
                            List<Community> communities = communityRepository.findByOrgIdAndStatus(enterpriseId, 1);
                            residenceCommunityIds = communities.stream().map(Community::getId).distinct().collect(Collectors.toList());//小区id
                        }

                        wheres.append(" and (h." + areaTag + " = ? or l.org_id = ? or l.community_id in ");
                        args.add(areaId);
                        args.add(hierarchyOrgId);
                        if (!residenceCommunityIds.isEmpty()) {
                            wheres.append(SqlUtils.foreachIn(residenceCommunityIds.size()) + ")");
                            args.addAll(residenceCommunityIds);
                        } else {
                            wheres.append("(null))");
                        }
                    } else {
                        wheres.append(" and (h.owner_mobile = ? or l.id in ");
                        args.add(phone);
                        if (!lockIds.isEmpty()) {
                            wheres.append(SqlUtils.foreachIn(lockIds.size()) + ")");
                            args.addAll(lockIds);
                        } else {
                            wheres.append("(null))");
                        }
                    }
                }

                if (bindType == 2) {//个人锁
                    List<SmartLockUser> lockUserList = smartLockUserRepository.findPersonLockUser(userId, phone);
                    List<Long> lockIds = lockUserList.stream().map(SmartLockUser::getLockId).distinct().collect(Collectors.toList());

                    if (loginType == 1) {
                        wheres.append(" and l.operator_org_id = ?");
                        args.add(enterpriseId);
                    } else {
                        wheres.append(" and (h.owner_mobile = ? or l.id in ");
                        args.add(phone);
                        if (!lockIds.isEmpty()) {
                            wheres.append(SqlUtils.foreachIn(lockIds.size()) + ")");
                            args.addAll(lockIds);
                        } else {
                            wheres.append("(null))");
                        }
                    }
                }

                //单位、个人
                wheres.append(" and l.bind_type = ? and l.bind_status = ?");
                args.add(bindType);
                args.add(bindType);
            }*/


            // 条件查询
            if (StringUtils.isNotBlank(search)) {
                where.append(" AND (l.`community_name` LIKE ? OR l.`match_user_name` LIKE ? OR l.`org_name` LIKE ? OR l.`name` LIKE ? OR l.`room_number` LIKE ?)");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
            }
            if (StringUtils.isNotBlank(name)) {
                where.append(" AND l.`name` LIKE ?");
                args.add("%" + name + "%");
            }
            if (StringUtils.isNotBlank(mac)) {
                where.append(" AND l.`mac` LIKE ?");
                args.add("%" + mac + "%");
            }
            if (type != null) {
                where.append(" AND l.`type` = ?");
                args.add(type);
            }
            if (StringUtils.isNotBlank(houseId)) {
                where.append(" AND l.`house_id` LIKE ?");
                args.add("%" + houseId + "%");
            }
            if (StringUtils.isNotBlank(communityId)) {
                where.append(" AND l.`community_id` = ?");
                args.add(communityId);
            }
            if (buildId != null) {
                where.append(" AND l.`build_id` = ?");
                args.add(buildId);
            }
            if (unitId != null) {
                where.append(" AND l.`unit_id` = ?");
                args.add(unitId);
            }
            if (StringUtils.isNotBlank(roomNumber)) {
                where.append(" AND l.`room_number` = ?");
                args.add(roomNumber);
            }
            if (signalLevel != null) {
                where.append(" AND l.`signal_level` = ?");
                args.add(signalLevel);
            }
            if (onlineStatus != null) {
                where.append(" AND l.`online_status` = ?");
                args.add(onlineStatus);
            }
            if (StringUtils.isNotBlank(orgName)) {
                where.append(" AND l.`org_name` LIKE ?");
                args.add("%" + orgName + "%");
            }
            if (StringUtils.isNotBlank(matchUserName)) {
                where.append(" AND l.`match_user_name` LIKE ?");
                args.add("%" + matchUserName + "%");
            }
            if (oauthNumber != null) {
                where.append(" AND l.`oauth_number` = ?");
                args.add(oauthNumber);
            }
            if (oauthStatus != null) {
                if (oauthStatus == 0) {
                    where.append(" AND (l.`oauth_number` = 0 or l.`oauth_number` is null)");
                } else if (oauthStatus == 1) {
                    where.append(" AND l.`oauth_number` > 0");
                }
            }
            if (mechineStatus != null) {
                where.append(" AND l.`mechine_status` = ?");
                args.add(mechineStatus);
            }

            if (leaseStatus != null) {

                if (leaseStatus == 1) {
                    where.append(" and ( h.lease_status = 1 OR h.lease_status = 2 OR h.lease_status = 3 OR h.lease_status = 4 )\n"
                            // 之前的sql，写了会重复查询出数据
                            // +
                            // "UNION ALL\n" +
                            // "SELECT l.id as lockId,l.brand_id as brandId, l.name,l.mac,l.type,l.house_id AS houseId,l.community_name AS communityName,l.build_name AS buildName,l.unit_name AS unitName,\n" +
                            // "l.room_number AS roomNumber,l.match_user_id AS matchUserId,l.match_user_name AS matchUserName,l.org_name AS orgName,l.oauth_number AS oauthNumber,l.mechine_status as mechineStatus,\n" +
                            // "l.reason,l.operator_time AS operatorTime,l.electric_quantity as electricQuantity,l.volume,l.signal_level as signalLevel,l.online_status as onlineStatus,\n" +
                            // "l.bind_type as bindType,l.is_person_permission as isPersonPermission,h.house_nature AS houseNature \n" +
                            // "FROM `saas_smart_lock` l\n" +
                            // "left join `saas_house` h \n" +
                            // "on l.`house_id` = h.id \n" +
                            // wheres +
                            // " and h.id in  ( select hh.id from (select h.id, CASE \n" +
                            // " WHEN ISNULL(uh.start_date) THEN\n" +
                            // " 0\n" +
                            // "ELSE\n" +
                            // "1\n" +
                            // "END  tt \n" +
                            // " from saas_house h left join m_match_user_house uh on h.id = uh.house_id) hh where hh.tt = 1" +")"
                    );
                }
                if (leaseStatus == 0) {
                    where.append(" and (h.lease_status is null or h.lease_status = 0)\n"
                            // 之前的sql，写了会重复查询出数据
                            // +
                            // "and h.id in  ( select hh.id from (select h.id, CASE \n" +
                            // "WHEN ISNULL(uh.start_date) THEN\n" +
                            // "0\n" +
                            // "ELSE\n" +
                            // "1\n" +
                            // "END  tt \n" +
                            // "from saas_house h left join m_match_user_house uh on h.id = uh.house_id) hh where hh.tt = 0) \n"
                    );
                }
            }


            // 总记录数
            Long total = jdbcTemplate.queryForObject(" SELECT COUNT(1) FROM( " + "SELECT l.id as lockId,l.brand_id as brandId, l.name,l.mac,l.type,l.house_id AS houseId,l.community_name AS communityName,l.build_name AS buildName,l.unit_name AS unitName,\n" +
                    " l.room_number AS roomNumber,l.match_user_id AS matchUserId,l.match_user_name AS matchUserName,l.org_name AS orgName,l.oauth_number AS oauthNumber,l.mechine_status as mechineStatus,\n" +
                    " l.reason,l.operator_time AS operatorTime,l.electric_quantity as electricQuantity,l.volume,l.signal_level as signalLevel,l.online_status as onlineStatus,\n" +
                    " l.bind_type as bindType,l.is_person_permission as isPersonPermission,h.house_nature AS houseNature FROM `saas_smart_lock` l left join `saas_house` h on l.`house_id` = h.id " +
                    where + ") a", args.toArray(), Long.class);
            log.info(" SELECT COUNT(1) FROM( " + "SELECT l.id as lockId,l.brand_id as brandId, l.name,l.mac,l.type,l.house_id AS houseId,l.community_name AS communityName,l.build_name AS buildName,l.unit_name AS unitName,\n" +
                    " l.room_number AS roomNumber,l.match_user_id AS matchUserId,l.match_user_name AS matchUserName,l.org_name AS orgName,l.oauth_number AS oauthNumber,l.mechine_status as mechineStatus,\n" +
                    " l.reason,l.operator_time AS operatorTime,l.electric_quantity as electricQuantity,l.volume,l.signal_level as signalLevel,l.online_status as onlineStatus,\n" +
                    " l.bind_type as bindType,l.is_person_permission as isPersonPermission,h.house_nature AS houseNature FROM `saas_smart_lock` l left join `saas_house` h on l.`house_id` = h.id " +
                    where + ") a", args.toArray());
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            String hhSql = " SELECT * FROM (" + "SELECT l.id as lockId,l.brand_id as brandId, l.name,l.mac,l.type,l.house_id AS houseId,l.community_name AS communityName,l.build_name AS buildName,l.unit_name AS unitName,\n" +
                    "l.room_number AS roomNumber,l.match_user_id AS matchUserId,l.match_user_name AS matchUserName,l.org_name AS orgName,l.oauth_number AS oauthNumber,l.mechine_status as mechineStatus,\n" +
                    "l.reason,l.operator_time AS operatorTime,l.electric_quantity as electricQuantity,l.volume,l.signal_level as signalLevel,l.online_status as onlineStatus,\n" +
                    "l.bind_type as bindType,l.is_person_permission as isPersonPermission,h.house_nature AS houseNature, h.lease_status AS leaseStatus \n" +
                    "FROM `saas_smart_lock` l left join `saas_house` h on l.`house_id` = h.id" +
                    where + ") a ORDER BY a.operatorTime " + SQL_PAGE;
            List<LockManagerListVO> lockList = jdbcTemplate.query(hhSql, new BeanPropertyRowMapper<>(LockManagerListVO.class), args.toArray());
            // 总授权人数
            List<Long> lockIds = lockList.stream().map(LockManagerListVO::getLockId).distinct().collect(Collectors.toList());
            if (CollectionUtil.isEmpty(lockIds)) {
                return resultBean;
            }
            String sql = "";
            if (bindType == 1) {
                sql = "SELECT lock_id AS lockId,COUNT(1) AS oauthCount FROM saas_smart_lock_auth WHERE lock_id IN "
                        + SqlUtils.foreachIn(lockIds.size()) + " AND bind_type = 0 GROUP BY lock_id";
            } else if (bindType == 2) {
                sql = "SELECT lock_id AS lockId,COUNT(1) AS oauthCount FROM saas_smart_lock_user WHERE lock_id IN "
                        + SqlUtils.foreachIn(lockIds.size()) + " AND del_status = 1 GROUP BY lock_id";
            }
            List<Map<String, Object>> mapList1 = jdbcTemplate.queryForList(sql, lockIds.toArray());

            // 个人锁管理员id
            List<Map<String, Object>> mapList2 = jdbcTemplate.queryForList("SELECT lock_id AS lockId,user_id as adminUserId FROM saas_smart_lock_user WHERE lock_id IN "
                    + SqlUtils.foreachIn(lockIds.size()) + " AND del_status = 1 AND user_type = 1 GROUP BY lock_id", lockIds.toArray());


            for (LockManagerListVO vo : lockList) {
                // 授权状态
                if (vo.getOauthNumber() != null && vo.getOauthNumber() > 0) {
                    vo.setOauthStatus(1);
                } else {
                    vo.setOauthStatus(0);
                }

                String operatorTime = vo.getOperatorTime();
                vo.setOperatorTime(operatorTime == null ? "" : DateUtils.format(operatorTime, DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));

                // 总授权人数
                for (Map map : mapList1) {
                    long lockId = Long.parseLong(map.get("lockId").toString());
                    int oauthCount = Integer.parseInt(map.get("oauthCount").toString());
                    if (vo.getLockId() == lockId) {
                        vo.setOauthCount(oauthCount);
                    }
                }

                // 个人锁管理员id
                for (Map map : mapList2) {
                    long lockId = Long.parseLong(map.get("lockId").toString());
                    String adminUserId = map.get("adminUserId").toString();
                    if (vo.getLockId() == lockId) {
                        vo.setAdminUserId(adminUserId);
                    }
                }

                // 单位标识
                if (vo.getBindType() == 1) {
                    if (loginType == 1) {
                        vo.setOrgFlag(1);
                    } else {
                        vo.setOrgFlag(0);
                    }
                } else {
                    if (loginType == 1) {
                        vo.setOrgFlag(0);
                    } else {
                        if (vo.getAdminUserId() != null && vo.getAdminUserId().equals(userId)) {
                            vo.setOrgFlag(1);
                        } else {
                            vo.setOrgFlag(0);
                        }
                    }
                }
            }
            for (LockManagerListVO lockManagerListVO : lockList) {
                Long lockId = lockManagerListVO.getLockId();
                String houseId1 = lockManagerListVO.getHouseId();
            }
            List<String> hdList = lockList.stream().filter(d -> d.getHouseNature() != 1).map(dd -> dd.getHouseId()).collect(Collectors.toList());
            List<String> hList = lockList.stream().filter(d -> d.getHouseNature() == 1).map(dd -> dd.getHouseId()).collect(Collectors.toList());
            // 公租房
            if (hList != null && !hList.isEmpty()) {
                List<House> byHouseNature = houseRepository.findByHouseNatureAndIdIn(1, hList);
                lockList.forEach(d -> {
                    byHouseNature.forEach(h -> {
                        if (d.getHouseId().equals(h.getId())) {
                            if (h.getLeaseStatus() == null || h.getLeaseStatus() == 0) {
                                d.setLease("未出租");
                                d.setLeaseStatus(0);
                            } else if (h.getLeaseStatus() == 1 || h.getLeaseStatus() == 2 || h.getLeaseStatus() == 3 || h.getLeaseStatus() == 4) {
                                d.setLease("已出租");
                                d.setLeaseStatus(1);
                            }
                        }
                    });
                });
            }


            // 非公租房   查询m_match_user_house  开始时间和结束时间不为空
            if (hdList != null && !hdList.isEmpty()) {
                String sql1 = " SELECT m.* from m_match_user_house m\n" +
                        " LEFT JOIN saas_house h " +
                        " ON h.id = m.house_id ";
                StringBuffer where1 = new StringBuffer(" WHERE 1=1 ");
                if (hdList != null && !hdList.isEmpty()) {
                    where1.append(" and house_id in " + SqlUtils.foreachIn(hdList.size()));
                }
                if (leaseStatus != null) {
                    if (leaseStatus == 0) {
                        where1.append(" and (m.start_date is NULL or m.end_date is NULL)");
                    } else if (leaseStatus == 1) {
                        where1.append(" and (m.start_date is TRUE or m.end_date is TRUE)");
                    }
                }
                // 新增房屋出租状态
                for (LockManagerListVO lockManagerListVO : lockList) {
                    Integer leaseStatus1 = lockManagerListVO.getLeaseStatus();
                    if (leaseStatus1 == 0) {
                        lockManagerListVO.setLease("未出租");
                    } else {
                        lockManagerListVO.setLease("1");
                        lockManagerListVO.setLease("已出租");
                    }
                }
                // List<MatchUserHouseVO> matchUserHouseVOS = jdbcTemplate.query(sql1 + where1, new BeanPropertyRowMapper<>(MatchUserHouseVO.class),hdList.toArray());
                // if (matchUserHouseVOS != null && !matchUserHouseVOS.isEmpty()){
                //	for (LockManagerListVO s : lockList) {
                //		boolean leaseflag = true;
                //		for (MatchUserHouseVO h : matchUserHouseVOS) {
                //			if (s.getHouseId().equals(h.getHouseId())) {
                //                if (h.getStartDate() == null || h.getEndDate() == null) {
                //                    s.setLease("未出租");
                //                    leaseflag = false;
                //                }
                //                if (h.getStartDate() != null && h.getEndDate() != null) {
                //                    s.setLease("已出租");
                //                    leaseflag = false;
                //                }
                //            }
                //		}
                //		if(leaseflag){
                //			s.setLease("未出租");
                //		}
                //	}
                //}else {
                //    lockList.forEach(s -> {
                //        hdList.forEach(item ->{
                //            if (item.equals(s.getHouseId())){
                //                s.setLease("未出租");
                //            }
                //        });
                //    });
                //}
            }

            // 如果是房屋管理员，那么就是未出租
            // communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType();
            // 新增智能锁批量授权状态：0可授权 1不可授权
            for (LockManagerListVO lockManagerListVO : lockList) {
                String houseId1 = lockManagerListVO.getHouseId();
                List<CommunityHouseUser> byCommunityHouseIdAndStatusAndType = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId1, 1, 3);
                if (!byCommunityHouseIdAndStatusAndType.isEmpty()) {
                    lockManagerListVO.setBatchOauth(0);
                } else {
                    lockManagerListVO.setBatchOauth(1);
                }
                // 智能锁冻结状态的判断冻结操作人
                // 非自动冻结才可以解冻
                if (lockManagerListVO.getMechineStatus() == 2) {
                    HouseLockFrozenLog lock = houseLockFrozenLogRepository.findByLockIdAndType(lockManagerListVO.getLockId(), 1);
                    if (null != lock) {
                        Integer operationState = lock.getOperationState();
                        lockManagerListVO.setFreezeOperator(operationState == null ? 1 : operationState);
                    } else {
                        LockFrozen lockFrozen = lockFrozenRepository.findByLockIdAndType(lockManagerListVO.getLockId(), 1);
                        if (lockFrozen != null) {
                            Integer operationState = lockFrozen.getOperationState();
                            lockManagerListVO.setFreezeOperator(operationState == null ? 1 : operationState);
                        }
                    }

                }

            }

            apiData.setData(lockList);
            apiData.setTotal(total);

            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("LockManagerService lockList Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }


    /**
     * 智能锁首页数据
     *
     * @param accessToken
     * @param houseId
     * @return
     */
    public ResultBean<List<LockStatusVo>> lockLeaderList(String accessToken, String houseId) {

        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            if (tokenRedisVo.getCertificationStatus() == null || tokenRedisVo.getCertificationStatus() == 0) {
                return ResultBean.failedResultOfNotRealName();
            }


            AppUser appUser = null;
            String userId = tokenRedisVo.getId();
            String phone = tokenRedisVo.getPhone();
            if (!StringUtils.isBlank(userId)) {
                appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
            }
            if (appUser == null) {
                return ResultBean.failedResultWithMsg("登录信息不存在");
            }
            if (StringUtils.isBlank(houseId)) {
                return ResultBean.failedResultOfParamWithMsg("房屋id为空");
            }
            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            // 获取房产属性，如果是合租房产需要通过合租房的父id去查询智能锁信息
            List<House> byIdAndStatus = houseRepository.findByIdAndStatus(houseId, 1);
            if (!byIdAndStatus.isEmpty()) {
                String housemateId = byIdAndStatus.get(0).getHousemateId();
                if (housemateId == null) {
                    args.add(houseId);
                    where.append(" AND ss.mobile = ?");
                    args.add(phone);
                } else {
                    args.add(housemateId);
                    where.append(" AND ss.mobile = ?");
                    args.add(phone);
                }
            }
          /*  String lockSql = "SELECT sl.mechine_status mechineStatus,sl.mac mac ,ss.lock_id ,ss.id lockAuthId,sl.electric_quantity electricQuantity,m.author_number authorNumber,m.use_number useNumber,m.password_validity as passwordValidity , m.create_time as createTime FROM saas_smart_lock_auth as ss\n" +
                    " LEFT JOIN m_match_user_lock_author as  m ON ss.house_id = m.house_id\n" +
                    " LEFT JOIN saas_smart_lock as sl ON m.house_id = sl.house_id\n" +
                    " WHERE ss.author_user_id = ? AND ss.house_id = ?";*/
            // List<LockStatusVo> vo = jdbcTemplate.query(lockSql, new BeanPropertyRowMapper<>(LockStatusVo.class), userId,houseId);
            String lockSql = "SELECT sl.id as lockId, sl.mechine_status mechineStatus,sl.mac mac , sl.brand_id brandId, ss.lock_id ,ss.id lockAuthId,sl.electric_quantity electricQuantity,m.author_number authorNumber,m.use_number useNumber,m.password_validity as passwordValidity , m.create_time as createTime FROM saas_smart_lock_auth as ss\n" +
                    " LEFT JOIN m_match_user_lock_author as  m ON ss.house_id = m.house_id\n" +
                    " LEFT JOIN saas_smart_lock as sl ON m.house_id = sl.house_id\n" +
                    " WHERE ss.house_id = ?";
            List<LockStatusVo> vo = jdbcTemplate.query(lockSql + where, new BeanPropertyRowMapper<>(LockStatusVo.class), args.toArray());
            // for (LockStatusVo lockStatusVo : vo) {
            //    Integer authorNumber = lockStatusVo.getAuthorNumber();
            //    Integer useNumber = lockStatusVo.getUseNumber();
            //}
            if (CollectionUtil.isEmpty(vo)) {
                return ResultBean.successfulResult(vo);
            }
            // Object pwdNum = redisTemplate.opsForValue().get("repeatPwd:" + vo.get(0).getLockId());
            // Integer usrPwd ;
            // if (ObjectUtil.isNull(pwdNum)) {
            //     usrPwd = 0;
            // }else {
            //     usrPwd = Integer.valueOf(pwdNum.toString());
            // }
            vo.forEach(m -> {
                // m.setUseRemainNumber(m.getAuthorNumber() - usrPwd);
                m.setUseRemainNumber(m.getAuthorNumber() - m.getUseNumber());
                Date createTime = m.getCreateTime();
                String time = DateUtils.getAddYEARTime(createTime, DateUtils.FORMAT_DATETIME_14, m.getPasswordValidity());
                m.setRemainingTime(time);
            });
            return ResultBean.successfulResult(vo);
        } catch (DataAccessException e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public ResultBean<Object> deleteLock(String accessToken, Long lockId) {
        try {
            log.info("deleteLock 智能锁删除 lockId={}", lockId);

            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            // 亚略特解绑
            if (smartLock.getBrandId() == 3L) {
                ResultBean<String> resultBean = smartLockYltService.merchantinfoUnBindLock(smartLock.getMac(), smartLock.getBrandId());
                if (!resultBean.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode()) && !resultBean.getMsg().equals("商户无对应的锁")) {
                    return ResultBean.failedResultWithMsg("解绑商户失败，不可删除");
                }
            }

            // 天网互联解绑
            if (smartLock.getBrandId() == 4) {
                // ResultBean<String> resultBean = fourEventHandleService.delete(smartLock.getMac(), smartLock.getBrandId());
                ResultBean<String> resultBean = smartLockTWHlService.deleteAll(smartLock.getMac(), lockId);
                if (!resultBean.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    return ResultBean.failedResultWithMsg("解绑商户失败，不可删除");
                }
            }

            // 优电互联解绑
            if (smartLock.getBrandId() == 6) {
                ResultBean<String> resultBean = smartLockYdService.deleteAll(smartLock.getSn(), lockId);
                if (!resultBean.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    return ResultBean.failedResultWithMsg("解绑商户失败，不可删除");
                }
            }


            // 删除合租房产下的子房产的智能锁与房屋信息
            Optional<SmartLock> byId = smartLockRepository.findById(lockId);
            if (byId.isPresent()) {
                String houseId = byId.get().getHouseId();
                List<House> byHousemateIdAndStatus = houseRepository.findByHousemateIdAndStatus(houseId, 1);
                if (!byHousemateIdAndStatus.isEmpty()) {
                    for (House housemateIdAndStatus : byHousemateIdAndStatus) {
                        String id = housemateIdAndStatus.getId();
                        smartLockRepository.deleteByHouseId(id);
                    }
                }
            }
            // 删除授权
            lockAppService.delAllAuth(accessToken, lockId);
            // 删除表数据
            smartLockRepository.deleteById(lockId);
            smartLockAuthRepository.deleteByLockId(lockId);
            smartLockUserRepository.deleteByLockId(lockId);
            smartLockPwdRepository.deleteByLockId(lockId);
            smartLockCardRepository.deleteByLockId(lockId);
            smartLockFingerprintRepository.deleteByLockId(lockId);
            smartLockFaceRepository.deleteByLockId(lockId);
            // 删除转个人待办事项
            backlogItemRepository.deleteByHouseIdAndType(smartLock.getHouseId(), BacklogItemTypeEnum.LOCK_BIND.getValue());

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerService deleteLock Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<LockHouseSettingVO> findLockOptions(String accessToken, Long lockId) {
        try {
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }

            LockHouseSetting lockHouseSetting = lockHouseSettingRepository.findByLockId(lockId);
            if (lockHouseSetting == null) {
                return ResultBean.failedResultWithMsg("智能锁设置信息不存在");
            }

            LockHouseSettingVO vo = new LockHouseSettingVO();
            vo.setLowPowerValue(lockHouseSetting.getLowPowerValue());
            vo.setLowPowerStatus(lockHouseSetting.getLowPowerStatus());
            vo.setStrangerOpenStatus(lockHouseSetting.getStrangerOpenStatus());
            vo.setPickProofType(lockHouseSetting.getPickProofType());
            vo.setPickProofStatus(lockHouseSetting.getPickProofStatus());
            vo.setDuressType(lockHouseSetting.getDuressType());
            vo.setDuressStatus(lockHouseSetting.getDuressStatus());
            vo.setVolumeValue(lockHouseSetting.getVolumeValue());

            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error("LockManagerService findLockOptions Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> lockOptionsSetup(String accessToken, Long lockId, Integer type, Integer value) {
        try {
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("设置类型为空");
            }

            Optional<SmartLock> smartLockOpt = smartLockRepository.findById(lockId);
            if (!smartLockOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = smartLockOpt.get();

            Optional<SmartLockBrand> smartLockBrandOpt = smartLockBrandRepository.findById(smartLock.getBrandId());
            if (!smartLockBrandOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁品牌不存在");
            }
            SmartLockBrand smartLockBrand = smartLockBrandOpt.get();

            if (type == 1) {// 低电量告警
                Integer lowPowerSet = smartLockBrand.getLowPowerSet();
                if (lowPowerSet == 0) {
                    return ResultBean.failedResultWithMsg("该智能锁品牌不支持低电量告警设置");
                } else if (lowPowerSet == 1) {
                    // 调用硬件接口
                }
            } else if (type == 2) {// 陌生人试开告警
                Integer strangerOpenAlarm = smartLockBrand.getStrangerOpenAlarm();
                if (strangerOpenAlarm == 0) {
                    return ResultBean.failedResultWithMsg("该智能锁品牌不支持陌生人试开告警设置");
                } else if (strangerOpenAlarm == 1) {
                    // 调用硬件接口
                }
            } else if (type == 3) {// 防撬告警
                Integer pickProofAlarm = smartLockBrand.getPickProofAlarm();
                if (pickProofAlarm == 0) {
                    return ResultBean.failedResultWithMsg("该智能锁品牌不支持防撬告警设置");
                } else if (pickProofAlarm == 1) {
                    // 调用硬件接口
                }
            } else if (type == 4) {// 胁迫告警
                Integer duressAlarm = smartLockBrand.getDuressAlarm();
                if (duressAlarm == 0) {
                    return ResultBean.failedResultWithMsg("该智能锁品牌不支持胁迫告警设置");
                } else if (duressAlarm == 1) {
                    // 调用硬件接口
                }
            } else if (type == 5) {// 音量调节
                Integer volumeSet = smartLockBrand.getVolumeSet();
                if (volumeSet == 0) {
                    return ResultBean.failedResultWithMsg("该智能锁品牌不支持音量调节设置");
                } else if (volumeSet == 1) {
                    // 调用硬件接口
                }
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerService lockOptionsSetup Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<TempPwdVO> findTempPwd(String accessToken, Long lockId) {
        try {
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }

            LockHouseSetting setting = lockHouseSettingRepository.findByLockId(lockId);
            if (setting == null) {
                return ResultBean.failedResultWithMsg("智能锁设置信息不存在");
            }

            Date date = new Date();
            TempPwdVO vo = new TempPwdVO();
            vo.setLockId(lockId);
            vo.setPassword(setting.getTempPwd());
            if (setting.getMinutes() != null) {
                // 结束时间
                Date endTime = DateUtils.getAddMinutesTime(setting.getPwdCreateTime(), setting.getMinutes());
                // 剩余时间
                if (date.compareTo(endTime) == -1) {
                    long NTime = date.getTime();
                    long OTime = endTime.getTime();
                    long minutes = (OTime - NTime) / 1000 / 60;
                    vo.setMinutes(minutes);
                } else {
                    vo.setMinutes(0L);
                }
            } else {
                vo.setMinutes(null);
            }

            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error("LockManagerService findTempPwd Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> authTempPwd(String accessToken, Long lockId, String password, Integer authType, Integer value) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }
            if (StringUtils.isBlank(password)) {
                return ResultBean.failedResultOfParamWithMsg("密码为空");
            }
            if (authType == null) {
                return ResultBean.failedResultOfParamWithMsg("授权类型为空");
            }
            if (value == null) {
                return ResultBean.failedResultOfParamWithMsg("输入值为空");
            }

            Optional<SmartLock> smartLockOpt = smartLockRepository.findById(lockId);
            if (!smartLockOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = smartLockOpt.get();

            LockHouseSetting setting = lockHouseSettingRepository.findByLockId(lockId);
            if (setting == null) {
                return ResultBean.failedResultWithMsg("智能锁设置信息不存在");
            }

            Date date = new Date();
            SmartLockVO smartLockVO = new SmartLockVO();
            smartLockVO.setPasswordType(2);// 临时密码
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setPassword(password);

            if (authType == 1) {// 有效次数
                smartLockVO.setStartTime(DateUtils.format(date, DateUtils.FORMAT_14));
                String addDaysTime = DateUtils.getAddDaysTime(date, DateUtils.FORMAT_14, 365 * 20);
                smartLockVO.setEndTime(addDaysTime);

                smartLockVO.setAuthType(LockAuthTypeEnum.TIMES_PASS.getValue());
                smartLockVO.setTimes(value);
            } else if (authType == 2) {// 有效时间
                smartLockVO.setStartTime(DateUtils.format(date, DateUtils.FORMAT_14));
                // 结束时间
                String endTime = DateUtils.getAddMinutesTime(date, DateUtils.FORMAT_14, value);
                smartLockVO.setEndTime(endTime);

                smartLockVO.setAuthType(LockAuthTypeEnum.NORMAL_PASS.getValue());
            }

            smartLockVO.setIndex(50);// 固定50
            smartLockVO.setDevMac(smartLock.getMac());

            SmartLockPwd smartLockPwd = null;
            // 重复设置时的处理
            if (StringUtils.isNotEmpty(setting.getTempPwd())) {
                smartLockPwd = new SmartLockPwd();
                smartLockPwd.setId(1l);
            }
            ResultBean<String> stringResultBean = smartLockBrandService.operationPassword(smartLockVO, smartLockPwd, smartLock.getBrandId());

            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();

            if (code != StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                log.error("LockAppService authTempPwd---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockManagerService authTempPwd---> callBack={}", resultData);
                setting.setTempPwd(password);
                setting.setPwdCreateTime(date);
                if (authType == 1) {// 有效次数
                    setting.setPwdNum(value);
                    setting.setTimes(value);
                    setting.setMinutes(null);
                } else if (authType == 2) {// 有效时间
                    setting.setMinutes(value);
                    setting.setPwdNum(null);
                    setting.setTimes(null);
                }
                setting.setOperatorId(userId);
                setting.setLastUpdateTime(date);
                lockHouseSettingRepository.save(setting);

                // 生成授权记录
                HouseLockOperatorLog houseLockOperatorLog = new HouseLockOperatorLog();
                houseLockOperatorLog.setLockId(lockId);
                houseLockOperatorLog.setType(HouseLockOperatorLogTypeEnum.PWD.getValue());
                houseLockOperatorLog.setOperatorId(userId);
                houseLockOperatorLog.setOperatorTime(date);
                houseLockOperatorLogRepository.save(houseLockOperatorLog);

                return ResultBean.successfulResultWithMsg("指令下发成功", null);
            }

        } catch (Exception e) {
            log.error("LockManagerService authTempPwd Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> authTempPwd(String accessToken, Long lockId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }

            Optional<SmartLock> smartLockOpt = smartLockRepository.findById(lockId);
            if (!smartLockOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = smartLockOpt.get();

            LockHouseSetting setting = lockHouseSettingRepository.findByLockId(lockId);
            if (setting == null) {
                return ResultBean.failedResultWithMsg("智能锁设置信息不存在");
            }

            Date date = new Date();
            SmartLockVO smartLockVO = new SmartLockVO();
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setStartTime(DateUtils.format(date, DateUtils.FORMAT_14));
            smartLockVO.setEndTime(DateUtils.getAddMinutesTime(date, DateUtils.FORMAT_14, 30));

            SmartLockPwd smartLockPwd = null;
            // 重复设置时的处理
            if (StringUtils.isNotEmpty(setting.getTempPwd())) {
                smartLockPwd = new SmartLockPwd();
                smartLockPwd.setId(1l);
            }

            ResultBean<List<DynamicPasswordVO>> resultBean = smartLockBrandService.getDynamicPassword(smartLockVO, smartLock.getBrandId());
            List<DynamicPasswordVO> resultData = resultBean.getResultData();
            String msg = resultBean.getMsg();
            String code = resultBean.getCode();

            if (code != StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                log.error("LockAppService authTempPwd---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockManagerService authTempPwd---> callBack={}", resultData);
                DynamicPasswordVO passwordVO = resultData.get(0);
                String password = passwordVO.getPassword();
                setting.setTempPwd(password);
                setting.setPwdCreateTime(date);
                if (smartLock.getBrandId() == 1) {
                    setting.setMinutes(30);
                } else if (smartLock.getBrandId() == 2) {
                    setting.setMinutes(120);
                }
                setting.setOperatorId(userId);
                setting.setLastUpdateTime(date);
                lockHouseSettingRepository.save(setting);

                // 生成授权记录
                HouseLockOperatorLog houseLockOperatorLog = new HouseLockOperatorLog();
                houseLockOperatorLog.setLockId(lockId);
                houseLockOperatorLog.setType(HouseLockOperatorLogTypeEnum.PWD.getValue());
                houseLockOperatorLog.setOperatorId(userId);
                houseLockOperatorLog.setOperatorTime(date);
                houseLockOperatorLogRepository.save(houseLockOperatorLog);

                return ResultBean.successfulResultWithMsg("指令下发成功", null);
            }
        } catch (Exception e) {
            log.error("LockManagerService authTempPwd Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    public ResultBean<Object> deleteTempPwd(String accessToken, Long lockId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }

            Optional<SmartLock> smartLockOpt = smartLockRepository.findById(lockId);
            if (!smartLockOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = smartLockOpt.get();

            LockHouseSetting setting = lockHouseSettingRepository.findByLockId(lockId);
            if (setting == null) {
                return ResultBean.failedResultWithMsg("智能锁设置信息不存在");
            }

            Date date = new Date();
            SmartLockVO smartLockVO = new SmartLockVO();
            smartLockVO.setPasswordType(2);// 临时密码
            smartLockVO.setSn(smartLock.getSn());
            smartLockVO.setIndex(50);// 固定50
            smartLockVO.setDevMac(smartLock.getMac());
            ResultBean<String> stringResultBean = smartLockBrandService.clearPassword(smartLockVO, smartLock.getBrandId(), "code", lockId);

            String resultData = stringResultBean.getResultData();
            String msg = stringResultBean.getMsg();
            String code = stringResultBean.getCode();

            if (code != StatusCode.SUCCESS_CODE_10000.getErrorCode()) {
                log.error("LockAppService deleteTempPwd---> " + msg);
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                log.info("LockManagerService deleteTempPwd---> callBack={}", resultData);
                setting.setTempPwd(null);
                setting.setPwdNum(null);
                setting.setTimes(null);
                setting.setPwdCreateTime(null);
                setting.setMinutes(null);
                setting.setOperatorId(userId);
                setting.setLastUpdateTime(date);
                lockHouseSettingRepository.save(setting);

                return ResultBean.successfulResultWithMsg("指令下发成功", null);
            }
        } catch (Exception e) {
            log.error("LockManagerService deleteTempPwd Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    public ResultBean<Object> factoryReset(String accessToken, FactoryResetVO vo) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (vo == null) {
                return ResultBean.failedResultOfParamWithMsg("参数为空");
            }
            if (vo.getLockId() == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id不存在");
            }
            if (StringUtils.isBlank(vo.getPhone())) {
                return ResultBean.failedResultOfParamWithMsg("手机号不存在");
            }
            if (StringUtils.isBlank(vo.getCode())) {
                return ResultBean.failedResultOfParamWithMsg("验证码不存在");
            }

            // 验证验证码
            String phone = redisService.getSmsCodeMobile(vo.getCode());
            if (!StringUtils.isBlank(phone)) {
                if (vo.getPhone().equals(phone)) {
                    Optional<SmartLock> smartLockOpt = smartLockRepository.findById(vo.getLockId());
                    if (!smartLockOpt.isPresent()) {
                        return ResultBean.failedResultWithMsg("智能锁不存在");
                    }
                    SmartLock smartLock = smartLockOpt.get();

                    Optional<SmartLockBrand> smartLockBrandOpt = smartLockBrandRepository.findById(smartLock.getBrandId());
                    if (!smartLockBrandOpt.isPresent()) {
                        return ResultBean.failedResultWithMsg("智能锁品牌不存在");
                    }
                    SmartLockBrand smartLockBrand = smartLockBrandOpt.get();

                    Integer factoryReset = smartLockBrand.getFactoryReset();
                    if (factoryReset == 0) {
                        return ResultBean.failedResultWithMsg("该智能锁品牌不支持恢复出厂设置");
                    } else if (factoryReset == 1) {
                        // 调用硬件接口

                    }

                } else {
                    return ResultBean.failedResultWithMsg("验证码已失效");
                }
            } else {
                return ResultBean.failedResultWithMsg("验证码未找到或已过期");
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerService factoryReset Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<ApiData<LockOperatorLogListVO>> operatorLogList(String accessToken, Long lockId, Integer pageNumber, Integer pageSize) {
        ResultBean<ApiData<LockOperatorLogListVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<LockOperatorLogListVO> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1");
            where.append(" and l.lock_id = ?");
            args.add(lockId);

            // 总记录数
            Long total = jdbcTemplate.queryForObject("SELECT count(1) FROM `saas_house_lock_operator_log` l" + where, args.toArray(), Long.class);
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<LockOperatorLogListVO> logList = jdbcTemplate.query("SELECT l.lock_id as lockId,l.type,l.operator_time as operatorTime FROM `saas_house_lock_operator_log` l" + where + LOCK_ORDER + SQL_PAGE,
                    new BeanPropertyRowMapper<>(LockOperatorLogListVO.class), args.toArray());

            for (LockOperatorLogListVO vo : logList) {
                String operatorTime = vo.getOperatorTime();
                vo.setOperatorTime(DateUtils.format(operatorTime, DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));
            }

            apiData.setData(logList);
            apiData.setTotal(total);

            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("LockManagerService operatorLogList Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }

    /**
     * 告警记录
     *
     * @param accessToken
     * @param search
     * @param date
     * @param matchUserName
     * @param communityId
     * @param buildId
     * @param unitId
     * @param roomNumber
     * @param alarmType     告警类型：1低电量告警 2防撬告警 3胁迫告警 4陌生人试开告警
     * @param beginDate
     * @param endDate
     * @param pageNumber
     * @param pageSize      机构可看权限内房屋告警记录 个人承租查自己住房告警记录
     */
    public ResultBean<ApiData<AlarmLogListVo>> alarmLogList(String accessToken, String search, String date,
                                                            String matchUserName, String communityId, Long buildId, Long unitId, String roomNumber, Integer alarmType,
                                                            String beginDate, String endDate,
                                                            Integer pageNumber, Integer pageSize) {
        ResultBean<ApiData<AlarmLogListVo>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<AlarmLogListVo> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            // 校验登录信息
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            Integer loginType = tokenRedisVo.getLoginType();

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            // 锁已删除的不展示数据
            where.append(" where s.id IS NOT NULL ");

            if (loginType == 1) {// 企业
                DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
                if (hierarchy == null) {
                    return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
                }
                List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(hierarchy.getId());
                List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签

                // 1、政府机构，根据区域标签所对应区域id查
                Long areaId = null;
                String areaTag = "province_id";
                if (enterpriseTagIds.contains(3L)) {
                    Long areaTagId = hierarchy.getTagId();// 区域标签
                    if (areaTagId == null) {
                        return ResultBean.failedResultWithMsg("机构所对应区域标签为空");
                    }
                    if (areaTagId == 1) {
                        areaTag = "province_id";
                    } else if (areaTagId == 2) {
                        areaTag = "city_id";
                    } else if (areaTagId == 3) {
                        areaTag = "district_id";
                    } else if (areaTagId == 4) {
                        areaTag = "street_id";
                    } else if (areaTagId == 5) {
                        areaTag = "community_id";
                    }
                    areaId = hierarchy.getAreaId();// 区域id
                }
                // 2、产权单位，根据orgId
                Long hierarchyOrgId = null;
                if (enterpriseTagIds.contains(2L)) {
                    hierarchyOrgId = hierarchy.getOrgId();
                }
                // 3、物业，查已绑定该物业的小区
                List<String> residenceCommunityIds = new ArrayList<>();
                if (enterpriseTagIds.contains(4L)) {
                    List<Community> communities = communityRepository.findByOrgIdAndStatus(enterpriseId, 1);
                    residenceCommunityIds = communities.stream().map(Community::getId).distinct().collect(Collectors.toList());// 小区id
                }

                where.append(" and ( h." + areaTag + " = ? or s.org_id = ? or s.match_user_id = ? or s.community_id in ");
                args.add(areaId);
                args.add(hierarchyOrgId);
                args.add(userId);
                if (!residenceCommunityIds.isEmpty()) {
                    where.append(SqlUtils.foreachIn(residenceCommunityIds.size()) + ")");
                    args.addAll(residenceCommunityIds);
                } else {
                    where.append("(?) )");
                    args.add(null);
                }
            } else {
                // 新增同住人能看到智能锁的告警记录
                List<SmartLockAuth> byAuthorUserId = smartLockAuthRepository.findByAuthorUserId(userId);
                if (CollectionUtil.isNotEmpty(byAuthorUserId)) {
                    where.append(" and s.match_user_id = ?");
                    String matchUserId = byAuthorUserId.get(0).getMatchUserId();
                    args.add(matchUserId);
                }
            }

            if (!StringUtils.isBlank(search)) {
                where.append(" AND (s.`match_user_name` LIKE ? or s.`community_name` LIKE ? OR s.`build_name` LIKE ? OR s.`unit_name` LIKE ?)");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
                args.add("%" + search + "%");
            }
            if (StringUtils.isNotBlank(date)) {
                where.append(" and la.alarm_time >= ? AND la.alarm_time < ?");
                args.add(date);
                args.add(DateUtils.getAddDaysTime(date, DateUtils.FORMAT_DATE_8, 1));
            }
            if (StringUtils.isNotBlank(matchUserName)) {
                where.append(" AND s.`match_user_name` LIKE ?");
                args.add("%" + matchUserName + "%");
            }
            if (StringUtils.isNotBlank(communityId)) {
                where.append(" AND s.`community_id` = ?");
                args.add(communityId);
            }
            if (buildId != null) {
                where.append(" AND s.`build_id` = ?");
                args.add(buildId);
            }
            if (unitId != null) {
                where.append(" AND s.`unit_id` = ?");
                args.add(unitId);
            }
            if (StringUtils.isNotBlank(roomNumber)) {
                where.append(" AND s.`room_number` = ?");
                args.add(roomNumber);
            }
            if (alarmType != null) {
                where.append(" AND la.`alarm_type` = ?");
                args.add(alarmType);
            }
            if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
                where.append(" and la.alarm_time >= ? AND la.alarm_time < ?");
                args.add(beginDate);
                args.add(DateUtils.getAddDaysTime(endDate, DateUtils.FORMAT_DATE_8, 1));
            }

            // 总记录数
            Long total = jdbcTemplate.queryForObject("SELECT count(1) FROM `saas_house_lock_alarm` la LEFT JOIN saas_smart_lock s ON la.lock_id = s.id left join saas_house h on la.house_id = h.id" + where, args.toArray(), Long.class);
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<AlarmLogListVo> logList = jdbcTemplate.query("SELECT s.match_user_name as matchUserName,s.community_id as communityId,s.community_name as communityName,\n" +
                            "s.build_id as buildId,s.build_name as buildName,s.unit_id as unitId,s.unit_name as unitName,s.room_number as roomNumber,la.alarm_type as alarmType,la.alarm_time as alarmTime " +
                            "FROM `saas_house_lock_alarm` la LEFT JOIN saas_smart_lock s ON la.lock_id = s.id left join saas_house h on la.house_id = h.id" + where + ALARM_ORDER + SQL_PAGE,
                    new BeanPropertyRowMapper<>(AlarmLogListVo.class), args.toArray());

            for (AlarmLogListVo vo : logList) {
                vo.setAlarmTime(DateUtils.format(vo.getAlarmTime(), DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));
            }

            apiData.setData(logList);
            apiData.setTotal(total);

            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("LockManagerService alarmLogList Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }

    /**
     * 未开门查询
     *
     * @param accessToken
     * @param lockId      锁id
     * @param communityId
     * @param buildId
     * @param unitId
     * @param roomNumber
     * @param type        开门类型:1内开门 2外开门
     * @param openDay     未开门天数
     * @param beginDay
     * @param endDay
     * @param pageNumber
     * @param pageSize    机构可看权限内房屋未开们记录 个人承租查自己住房未开门记录
     */
    public ResultBean<ApiData<LockUnOpenLogVO>> lockUnOpenLog(String accessToken, Long lockId, String communityId, Long buildId, Long unitId, String roomNumber,
                                                              Integer type, Integer openDay, Integer beginDay, Integer endDay, Integer pageNumber, Integer pageSize, String matchUserName) {
        ResultBean<ApiData<LockUnOpenLogVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<LockUnOpenLogVO> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            // 校验登录信息
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            Integer loginType = tokenRedisVo.getLoginType();


            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1");

            if (lockId != null) { // 单个
                where.append(" AND l.`id` = ?");
                args.add(lockId);
            } else {

                if (loginType == 1) {// 企业登录
                    DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
                    if (hierarchy == null) {
                        return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
                    }
                    List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(hierarchy.getId());
                    List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签

                    // 1、政府机构，根据区域标签所对应区域id查
                    Long areaId = null;
                    String areaTag = "province_id";
                    if (enterpriseTagIds.contains(3L)) {
                        Long areaTagId = hierarchy.getTagId();// 区域标签
                        if (areaTagId == null) {
                            return ResultBean.failedResultWithMsg("机构所对应区域标签为空");
                        }
                        if (areaTagId == 1) {
                            areaTag = "province_id";
                        } else if (areaTagId == 2) {
                            areaTag = "city_id";
                        } else if (areaTagId == 3) {
                            areaTag = "district_id";
                        } else if (areaTagId == 4) {
                            areaTag = "street_id";
                        } else if (areaTagId == 5) {
                            areaTag = "community_id";
                        }
                        areaId = hierarchy.getAreaId();// 区域id
                    }
                    // 2、产权单位，根据orgId
                    Long hierarchyOrgId = null;
                    if (enterpriseTagIds.contains(2L)) {
                        hierarchyOrgId = hierarchy.getOrgId();
                    }
                    // 3、物业，查已绑定该物业的小区
                    List<String> residenceCommunityIds = new ArrayList<>();
                    if (enterpriseTagIds.contains(4L)) {
                        List<Community> communities = communityRepository.findByOrgIdAndStatus(enterpriseId, 1);
                        residenceCommunityIds = communities.stream().map(Community::getId).distinct().collect(Collectors.toList());// 小区id
                    }

                    where.append(" and ( h." + areaTag + " = ? or l.org_id = ? or l.match_user_id = ? or l.community_id in ");
                    args.add(areaId);
                    args.add(hierarchyOrgId);
                    args.add(userId);
                    if (!residenceCommunityIds.isEmpty()) {
                        where.append(SqlUtils.foreachIn(residenceCommunityIds.size()) + ")");
                        args.addAll(residenceCommunityIds);
                    } else {
                        where.append("(?) )");
                        args.add(null);
                    }
                } else {
                    where.append(" and l.match_user_id = ?");
                    args.add(userId);
                }


            }
            if (StringUtils.isNotBlank(communityId)) {
                where.append(" AND l.`community_id` = ?");
                args.add(communityId);
            }
            if (buildId != null) {
                where.append(" AND l.`build_id` = ?");
                args.add(buildId);
            }
            if (unitId != null) {
                where.append(" AND l.`unit_id` = ?");
                args.add(unitId);
            }
            if (StringUtils.isNotBlank(roomNumber)) {
                where.append(" AND l.`room_number` = ?");
                args.add(roomNumber);
            }
            if (type != null) {
                where.append(" AND s.`type` = ?");
                args.add(type);
            }
            if (openDay != null) {
                where.append(" AND s.`open_day` <= ?");
                args.add(openDay);
            }
            if (beginDay != null && endDay != null) {
                where.append(" and s.open_day >= ? AND s.open_day <= ?");
                args.add(beginDay);
                args.add(endDay);
            }
            if (StringUtils.isNotBlank(matchUserName)) {
                where.append(" AND l.match_user_name LIKE '%" + matchUserName + "%'  ");
            }


            // 总记录数
            Long total = jdbcTemplate.queryForObject("SELECT count(1) FROM `saas_smart_lock` l LEFT JOIN saas_house_lock_open_statistics s ON l.id = s.lock_id left join saas_house h on l.house_id = h.id " + where, args.toArray(), Long.class);
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<LockUnOpenLogVO> logList = jdbcTemplate.query("SELECT l.community_id as communityId,l.community_name as communityName,\n" +
                            "l.build_id as buildId,l.build_name as buildName,l.unit_id as unitId,l.unit_name as unitName,l.room_number as roomNumber,\n" +
                            "s.type,s.open_day as openDay, l.match_user_name as matchUserName \n" +
                            "FROM `saas_smart_lock` l LEFT JOIN saas_house_lock_open_statistics s ON l.id = s.lock_id left join saas_house h on l.house_id = h.id " + where + SQL_PAGE,
                    new BeanPropertyRowMapper<>(LockUnOpenLogVO.class), args.toArray());
            apiData.setData(logList);
            apiData.setTotal(total);

            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("LockManagerService lockUnOpenLog Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }

    public ResultBean<Object> setPersonPermission(Long lockId, Integer type) {
        try {
            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock lock = lockOptional.get();

            lock.setIsPersonPermission(type);
            smartLockRepository.save(lock);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerService setPersonPermission Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 清理房屋所有授权, 不解绑房屋与锁的绑定
     *
     * @param accessToken
     * @param lockId
     * @return
     * @throws CustomException
     * @author shun
     * @date 2022年7月1日
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public ResultBean<Object> deleteLockAuth(String accessToken, Long lockId) throws CustomException {
        try {
            log.info("deleteLock 智能锁删除 lockId={}", lockId);

            if (lockId == null) {
                return ResultBean.failedResultOfParamWithMsg("智能锁id为空");
            }

            Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
            if (!lockOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOptional.get();

            // 亚略特
            if (smartLock.getBrandId() == 3L) {
                // 查看锁授权情况，如果有未取消的授权，需要取消所有授权
                ResultBean<List<YltAuthorizationRecordVO>> authListResult = smartLockYltService.select(smartLock.getMac(), smartLock.getBrandId());
                if (!authListResult.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    return ResultBean.failedResultWithMsg(authListResult.getMsg());
                }

                if (authListResult.getResultData() != null) {
                    List<YltAuthorizationRecordVO> voList = authListResult.getResultData();
                    if (voList.size() > 0) {
                        // 清除锁所有授权
                        SmartLockVO lockVO = new SmartLockVO();
                        lockVO.setSn(smartLock.getMac());
                        ResultBean<String> resultBean = smartLockYltService.deauthorize(lockVO, smartLock.getBrandId(), 2);
                        if (!resultBean.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                            log.info("退租, 清除智能锁全部权限成功, imei={}, brandId={}", smartLock.getMac(), smartLock.getBrandId());
                        }
                    }
                }
            }

            // 删除授权
            lockAppService.delAllAuth(accessToken, lockId);
            // 删除表数据
            smartLockAuthRepository.deleteByLockId(lockId);
            smartLockUserRepository.deleteByLockId(lockId);
            smartLockPwdRepository.deleteByLockId(lockId);
            smartLockCardRepository.deleteByLockId(lockId);
            smartLockFingerprintRepository.deleteByLockId(lockId);
            smartLockFaceRepository.deleteByLockId(lockId);
            // 删除转个人待办事项
            backlogItemRepository.deleteByHouseIdAndType(smartLock.getHouseId(), BacklogItemTypeEnum.LOCK_BIND.getValue());

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockManagerService deleteLock Exception = {}" + e.getMessage(), e);
            throw new CustomException("清理锁授权异常");
        }
    }

    public ResultBean<ApiData<AlarmLogListVo>> alarmLogListV2(String accessToken, Long lockId, Integer alarmType, String endDate, Integer pageNumber, Integer pageSize) {

        ResultBean<ApiData<AlarmLogListVo>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<AlarmLogListVo> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            // 校验登录信息
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (ObjectUtil.isNull(lockId)) {
                return ResultBean.failedResultWithMsg("参数有误，请检查锁id。");
            }

            // 验证该用户有权查看该锁的告警记录
            SmartLockAuth auth = smartLockAuthRepository.findByAuthorUserIdAndLockId(userId, lockId);
            if (ObjectUtil.isNull(auth)) {
                return ResultBean.failedResultWithMsg("您无权查看该锁的告警记录！");
            }

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1");

            if (ObjectUtil.isNotNull(lockId)) {
                where.append(" and la.lock_id = ?");
                args.add(lockId);
            }

            if (StringUtils.isNotBlank(endDate)) {
                where.append(" and la.alarm_time < ?");
                args.add(endDate);
            }

            if (alarmType != null) {
                where.append(" AND la.`alarm_type` = ?");
                args.add(alarmType);
            }

            // 总记录数
            Long total = jdbcTemplate.queryForObject("SELECT count(1) FROM `saas_house_lock_alarm` la " + where, args.toArray(), Long.class);

            if (total == 0) {
                return resultBean;
            }
            args.add(pageSize);
            args.add(pageNumber * pageSize);

            List<AlarmLogListVo> logList = jdbcTemplate.query("select la.alarm_type as alarmType, la.alarm_time as alarmTime, l.community_name, l.build_name, l.unit_name, l.room_number, l.match_user_name from `saas_house_lock_alarm` la left join `saas_house` h on la.house_id = h.id left join `saas_smart_lock` l on la.house_id = l.house_id " + where + ALARM_ORDER + SQL_PAGE,
                    new BeanPropertyRowMapper<>(AlarmLogListVo.class), args.toArray());
            apiData.setData(logList);
            apiData.setTotal(total);
            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("LockManagerService alarmLogList Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }

}



